docs: preserve reviewed NetKingdom session artifacts
This commit is contained in:
parent
19011a9516
commit
d6168526c5
50 changed files with 11801 additions and 0 deletions
|
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"systems": [
|
||||
{
|
||||
"id": "forgejo",
|
||||
"name": "Synthetic test only",
|
||||
"resource_types": [
|
||||
{
|
||||
"name": "application"
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"name": "application.access"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjects": [],
|
||||
"resource_manifests": [
|
||||
{
|
||||
"id": "forgejo.synthetic.resources",
|
||||
"system": "forgejo",
|
||||
"resources": [
|
||||
{
|
||||
"id": "application:forgejo",
|
||||
"type": "application",
|
||||
"attributes": {
|
||||
"identity_issuer": "https://issuer.invalid",
|
||||
"tenant": "tenant:synthetic"
|
||||
}
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
"application.access"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,729 @@
|
|||
package decision
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/callerauth"
|
||||
"github.com/netkingdom/access-engine/internal/policy"
|
||||
"github.com/netkingdom/access-engine/internal/registry"
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/internal/taskexecution"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// Engine evaluates deterministic standalone authorization checks against a
|
||||
// local registry and one validated policy package.
|
||||
type Engine struct {
|
||||
store *registry.Store
|
||||
policy *policy.Package
|
||||
mu sync.RWMutex
|
||||
history map[string]api.DecisionEnvelope
|
||||
log DecisionRecorder
|
||||
clock func() time.Time
|
||||
signingKey ed25519.PrivateKey
|
||||
signingKID string
|
||||
}
|
||||
|
||||
// DecisionRecorder persists decision envelopes.
|
||||
type DecisionRecorder interface {
|
||||
Append(api.DecisionEnvelope) error
|
||||
}
|
||||
|
||||
// BatchRecorder commits several decisions in one durable write.
|
||||
type BatchRecorder interface {
|
||||
AppendBatch([]api.DecisionEnvelope) error
|
||||
}
|
||||
|
||||
// ErrRecordNotCommitted means a decision was withheld because its required
|
||||
// record did not commit (GH-DEC-2026-024). The service answers 503; this is
|
||||
// unavailability, never a substitute authorization verdict.
|
||||
var ErrRecordNotCommitted = errors.New("decision withheld: record not committed")
|
||||
|
||||
// ListAllowedRequest describes a deterministic list_allowed call.
|
||||
type ListAllowedRequest struct {
|
||||
Subject api.SubjectRef `json:"subject"`
|
||||
Action string `json:"action"`
|
||||
System string `json:"system,omitempty"`
|
||||
ResourceType string `json:"resource_type,omitempty"`
|
||||
Filters map[string]any `json:"filters,omitempty"`
|
||||
Context map[string]any `json:"context,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty"`
|
||||
}
|
||||
|
||||
// Explanation is a compact explanation view over a recorded decision.
|
||||
type Explanation struct {
|
||||
DecisionID string `json:"decision_id"`
|
||||
Effect api.DecisionEffect `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Summary string `json:"summary"`
|
||||
Subject api.SubjectRef `json:"subject"`
|
||||
Resource api.ResourceRef `json:"resource"`
|
||||
PolicyPackage string `json:"policy_package,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty"`
|
||||
MatchedRule string `json:"matched_rule,omitempty"`
|
||||
Diagnostics map[string]any `json:"diagnostics,omitempty"`
|
||||
Caring *api.CaringDecisionMetadata `json:"caring,omitempty"`
|
||||
}
|
||||
|
||||
// NewEngine creates a standalone decision engine.
|
||||
func NewEngine(store *registry.Store, policyPackage *policy.Package) (*Engine, error) {
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("registry store is required")
|
||||
}
|
||||
if policyPackage == nil {
|
||||
return nil, fmt.Errorf("policy package is required")
|
||||
}
|
||||
if !policyPackage.Valid {
|
||||
return nil, fmt.Errorf("policy package %q is not valid", policyPackage.Metadata.ID)
|
||||
}
|
||||
return &Engine{
|
||||
store: store,
|
||||
policy: policyPackage,
|
||||
history: make(map[string]api.DecisionEnvelope),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetEnvelopeSigningKey installs an owner-custodied key before serving requests.
|
||||
// The key is copied so caller mutation cannot change the admitted signer.
|
||||
func (e *Engine) SetEnvelopeSigningKey(key ed25519.PrivateKey, kid string) error {
|
||||
if len(key) != ed25519.PrivateKeySize || strings.TrimSpace(kid) == "" {
|
||||
return fmt.Errorf("valid Ed25519 private key and kid are required")
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.signingKey = append(ed25519.PrivateKey(nil), key...)
|
||||
e.signingKID = kid
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDecisionLog attaches a local decision recorder to the engine.
|
||||
func (e *Engine) SetDecisionLog(log DecisionRecorder) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.log = log
|
||||
}
|
||||
|
||||
// SetClock overrides the engine clock. Tests use this to pin allow lifetimes.
|
||||
func (e *Engine) SetClock(clock func() time.Time) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.clock = clock
|
||||
}
|
||||
|
||||
func (e *Engine) now() time.Time {
|
||||
e.mu.RLock()
|
||||
clock := e.clock
|
||||
e.mu.RUnlock()
|
||||
if clock != nil {
|
||||
return clock().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
// decide evaluates one request without recording it.
|
||||
func (e *Engine) decide(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
normalized, facts := e.normalizeRequest(request)
|
||||
|
||||
expectation, err := e.policy.Evaluate(ctx, normalized)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
|
||||
envelope := e.envelope(ctx, normalized, request, expectation, facts)
|
||||
e.mu.RLock()
|
||||
key, kid := e.signingKey, e.signingKID
|
||||
e.mu.RUnlock()
|
||||
if len(key) != 0 {
|
||||
if err := sign.Sign(&envelope, key, kid); err != nil {
|
||||
return api.DecisionEnvelope{}, fmt.Errorf("decision signing failed: %w", err)
|
||||
}
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// IsServicePilot selects the existing exact source package, never a request flag.
|
||||
func (e *Engine) IsServicePilot() bool {
|
||||
return e.policy.Metadata.ID == taskexecution.ServicePilotPackageID && e.policy.Metadata.Version == taskexecution.ServicePilotPackageVersion
|
||||
}
|
||||
func (e *Engine) IsTrustedServicePilot() bool {
|
||||
return e.policy.Metadata.ID == taskexecution.ServicePilotPackageID && e.policy.Metadata.Version == taskexecution.TrustedServicePilotPackageVersion
|
||||
}
|
||||
func (e *Engine) IsTaskPin() bool { return e.IsServicePilot() || e.IsTrustedServicePilot() }
|
||||
|
||||
// ErrServicePilotUnavailable withholds any result that is not this B1 slice's
|
||||
// signed DENY. Provider joins and executable eligibility remain unimplemented.
|
||||
var ErrServicePilotUnavailable = errors.New("service pilot source path unavailable")
|
||||
|
||||
// CheckServicePilot records only a signed DENY after authenticating the exact
|
||||
// immutable service input. It does not validate Approval facts or grant an act.
|
||||
func (e *Engine) CheckServicePilot(ctx context.Context, input taskexecution.ServiceInput) (api.DecisionEnvelope, error) {
|
||||
if !e.IsServicePilot() {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
request, err := input.RequestAt(e.now())
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
envelope, err := e.decide(callerauth.WithRecord(ctx, input.Caller()), request)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
if envelope.Effect != api.DecisionEffectDeny || envelope.Signature == nil || envelope.Signature.Mode != api.EnvelopeSignatureSigned {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
if err := e.recordDecisions([]api.DecisionEnvelope{envelope}); err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// Check evaluates one subject/action/resource request. The decision is
|
||||
// released only after its required record commits (GH-DEC-2026-024).
|
||||
func (e *Engine) Check(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
decision, err := e.decide(ctx, request)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
if err := e.recordDecisions([]api.DecisionEnvelope{decision}); err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// BatchCheck evaluates one subject/action/context tuple against resources in
|
||||
// request order, and commits the whole batch in one durable write.
|
||||
func (e *Engine) BatchCheck(ctx context.Context, request api.BatchCheckRequest) ([]api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return nil, ErrServicePilotUnavailable
|
||||
}
|
||||
decisions := make([]api.DecisionEnvelope, 0, len(request.Resources))
|
||||
for _, resource := range request.Resources {
|
||||
decision, err := e.decide(ctx, api.CheckRequest{
|
||||
ID: request.ID,
|
||||
Tenant: request.Tenant,
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: resource,
|
||||
Context: request.Context,
|
||||
PolicyVersion: request.PolicyVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := e.recordDecisions(decisions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decisions, nil
|
||||
}
|
||||
|
||||
// ListAllowed evaluates candidate resources and returns only allow decisions.
|
||||
func (e *Engine) ListAllowed(ctx context.Context, request ListAllowedRequest) ([]api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return nil, ErrServicePilotUnavailable
|
||||
}
|
||||
candidates := e.store.ResourceRefs(request.System, request.ResourceType)
|
||||
decisions := make([]api.DecisionEnvelope, 0, len(candidates))
|
||||
for _, resource := range candidates {
|
||||
if !resourceMatchesFilters(resource, request.Filters) {
|
||||
continue
|
||||
}
|
||||
decision, err := e.decide(ctx, api.CheckRequest{
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: resource,
|
||||
Context: request.Context,
|
||||
PolicyVersion: request.PolicyVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := e.recordDecisions(decisions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allowed := make([]api.DecisionEnvelope, 0, len(decisions))
|
||||
for _, decision := range decisions {
|
||||
if decision.Effect == api.DecisionEffectAllow {
|
||||
allowed = append(allowed, decision)
|
||||
}
|
||||
}
|
||||
return allowed, nil
|
||||
}
|
||||
|
||||
// Explain returns a CARING-aware explanation for a decision recorded by this
|
||||
// engine instance. P2.6 replaces this in-memory history with the local log.
|
||||
func (e *Engine) Explain(decisionID string) (Explanation, error) {
|
||||
e.mu.RLock()
|
||||
decision, ok := e.history[decisionID]
|
||||
e.mu.RUnlock()
|
||||
if !ok {
|
||||
return Explanation{}, fmt.Errorf("decision %q not found", decisionID)
|
||||
}
|
||||
|
||||
return ExplainEnvelope(decision), nil
|
||||
}
|
||||
|
||||
// ExplainEnvelope returns the same explanation shape for an already-loaded
|
||||
// decision envelope.
|
||||
func ExplainEnvelope(decision api.DecisionEnvelope) Explanation {
|
||||
return Explanation{
|
||||
DecisionID: decision.ID,
|
||||
Effect: decision.Effect,
|
||||
Reason: decision.Reason,
|
||||
Summary: explanationSummary(decision),
|
||||
Subject: decision.Subject,
|
||||
Resource: decision.Resource,
|
||||
PolicyPackage: decision.Provenance.PolicyPackage,
|
||||
PolicyVersion: decision.Provenance.PolicyVersion,
|
||||
MatchedRule: decision.MatchedRule,
|
||||
Diagnostics: decision.Diagnostics,
|
||||
Caring: decision.Caring,
|
||||
}
|
||||
}
|
||||
|
||||
type registryFacts struct {
|
||||
subjectFound bool
|
||||
resourceFound bool
|
||||
subject api.Subject
|
||||
resource api.Resource
|
||||
matchedRelationship string
|
||||
descriptor *api.CaringAccessDescriptor
|
||||
// overriddenByRegistry names request attribute keys whose caller-supplied
|
||||
// value was displaced by a registry fact. Empty on an honest request; a
|
||||
// non-empty list means the caller asserted something the registry contradicts,
|
||||
// which is worth seeing even though the registry won (FLEX-DEC-2026-012).
|
||||
overriddenByRegistry []string
|
||||
}
|
||||
|
||||
func (e *Engine) normalizeRequest(request api.CheckRequest) (api.CheckRequest, registryFacts) {
|
||||
normalized := request
|
||||
facts := registryFacts{}
|
||||
|
||||
overridden := []string{}
|
||||
|
||||
if normalized.Tenant != "" {
|
||||
if normalized.Subject.Tenant == "" {
|
||||
normalized.Subject.Tenant = normalized.Tenant
|
||||
}
|
||||
if normalized.Resource.Tenant == "" {
|
||||
normalized.Resource.Tenant = normalized.Tenant
|
||||
}
|
||||
}
|
||||
|
||||
if subject, ok := e.store.Subject(request.Subject.ID); ok {
|
||||
facts.subjectFound = true
|
||||
facts.subject = subject
|
||||
normalized.Subject = enrichSubjectRef(request.Subject, subject, &overridden)
|
||||
}
|
||||
|
||||
if resource, ok := e.store.Resource(request.Resource.System, request.Resource.ID); ok {
|
||||
facts.resourceFound = true
|
||||
facts.resource = resource
|
||||
normalized.Resource = enrichResourceRef(request.Resource, resource, &overridden)
|
||||
}
|
||||
|
||||
if normalized.CaringContext != nil {
|
||||
descriptor := *normalized.CaringContext
|
||||
facts.descriptor = &descriptor
|
||||
facts.overriddenByRegistry = overridden
|
||||
return normalized, facts
|
||||
}
|
||||
|
||||
facts.overriddenByRegistry = overridden
|
||||
|
||||
if descriptor, relationshipID := e.matchCaringDescriptor(normalized, facts); descriptor != nil {
|
||||
facts.descriptor = descriptor
|
||||
facts.matchedRelationship = relationshipID
|
||||
normalized.CaringContext = descriptor
|
||||
} else if facts.resourceFound && facts.resource.Caring != nil {
|
||||
descriptor := *facts.resource.Caring
|
||||
facts.descriptor = &descriptor
|
||||
normalized.CaringContext = &descriptor
|
||||
}
|
||||
|
||||
return normalized, facts
|
||||
}
|
||||
|
||||
func (e *Engine) matchCaringDescriptor(request api.CheckRequest, facts registryFacts) (*api.CaringAccessDescriptor, string) {
|
||||
candidates := []string{request.Subject.ID}
|
||||
if facts.subjectFound {
|
||||
candidates = append(candidates, facts.subject.Groups...)
|
||||
}
|
||||
|
||||
for _, relationship := range e.store.RelationshipsForObject(request.Resource.ID) {
|
||||
if relationship.Caring == nil {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(candidates, relationship.Subject) {
|
||||
continue
|
||||
}
|
||||
if relationship.System != "" && relationship.System != request.Resource.System {
|
||||
continue
|
||||
}
|
||||
if relationship.Tenant != "" && request.Resource.Tenant != "" && relationship.Tenant != request.Resource.Tenant {
|
||||
continue
|
||||
}
|
||||
descriptor := *relationship.Caring
|
||||
return &descriptor, relationship.ID
|
||||
}
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
// enrichSubjectRef overlays registry facts onto the subject the caller sent.
|
||||
//
|
||||
// Registry facts WIN. A value in the registry is an authority statement; the
|
||||
// same key on the request is the caller's proposal about itself. Letting the
|
||||
// proposal survive made a registry ceiling advisory — see FLEX-DEC-2026-012,
|
||||
// where a caller supplying resource.attributes.allowed_subjects authorized a
|
||||
// subject the registry did not know.
|
||||
//
|
||||
// Keys the registry does not define still pass through from the request. That
|
||||
// residual is stated in docs/request-enrichment.md rather than fixed here: a
|
||||
// policy reading a key its manifest omits is consuming caller input, and the
|
||||
// structural fix is separating the two namespaces (FLEX-WP-0025).
|
||||
func enrichSubjectRef(ref api.SubjectRef, subject api.Subject, overridden *[]string) api.SubjectRef {
|
||||
out := ref
|
||||
// subject.Type is deliberately NOT overwritten, unlike every other registry
|
||||
// fact here. The registry's Type is CARING vocabulary (Human, Agent,
|
||||
// Automation, Service); the request's is the protected system's actor
|
||||
// vocabulary (service, adm, agt, atm). They are two different fields sharing
|
||||
// a name, and substituting one for the other is translation rather than
|
||||
// identity — the error GH-DEC-2026-008 ruled against. Making the registry win
|
||||
// here denied every secrets-engine allow, because "Service" is not "service".
|
||||
//
|
||||
// The residual is that a caller can still assert its own subject.type and
|
||||
// packages branch on it. That is not fixable by overwriting from a different
|
||||
// vocabulary; it needs the two fields separated. FLEX-WP-0025.
|
||||
if out.Type == "" {
|
||||
out.Type = subject.Type
|
||||
}
|
||||
if subject.Tenant != "" {
|
||||
out.Tenant = subject.Tenant
|
||||
}
|
||||
out.Attributes = copyMap(out.Attributes)
|
||||
setAuthoritative(out.Attributes, "display_name", subject.DisplayName, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "organization_relation", subject.OrganizationRelation, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "roles", subject.Roles, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "groups", subject.Groups, "subject", overridden)
|
||||
setAuthoritatives(out.Attributes, subject.Claims, "subject", overridden)
|
||||
setAuthoritatives(out.Attributes, subject.Metadata, "subject", overridden)
|
||||
return out
|
||||
}
|
||||
|
||||
// enrichResourceRef overlays registry facts onto the resource the caller sent.
|
||||
// Registry facts win, for the reason given on enrichSubjectRef: ops-warden's
|
||||
// max_ttl_hours, allowed_subjects, and allowed_principals are ceilings and
|
||||
// allowlists, and a ceiling a caller can raise is not a ceiling.
|
||||
func enrichResourceRef(ref api.ResourceRef, resource api.Resource, overridden *[]string) api.ResourceRef {
|
||||
out := ref
|
||||
if resource.Type != "" {
|
||||
out.Type = resource.Type
|
||||
}
|
||||
out.Attributes = copyMap(out.Attributes)
|
||||
setAuthoritative(out.Attributes, "path", resource.Path, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "parent", resource.Parent, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "labels", resource.Labels, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "trust_zone", resource.TrustZone, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "owner", resource.Owner, "resource", overridden)
|
||||
setAuthoritatives(out.Attributes, resource.Attributes, "resource", overridden)
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *Engine) envelope(ctx context.Context, request, submitted api.CheckRequest, expectation api.DecisionExpectation, facts registryFacts) api.DecisionEnvelope {
|
||||
envelope := api.DecisionEnvelope{
|
||||
RequestID: request.ID,
|
||||
Effect: expectation.Effect,
|
||||
Reason: expectation.Reason,
|
||||
MatchedPolicyVersion: e.policy.Metadata.Version,
|
||||
MatchedRule: expectation.Reason,
|
||||
Resource: request.Resource,
|
||||
Subject: request.Subject,
|
||||
Binding: api.NewDecisionBindingFor(request, submitted),
|
||||
Obligations: expectation.Obligations,
|
||||
Diagnostics: map[string]any{
|
||||
"action": request.Action,
|
||||
"policy_package": e.policy.Metadata.ID,
|
||||
"policy_status": e.policy.Metadata.Status,
|
||||
"registry_subject": facts.subjectFound,
|
||||
"registry_resource": facts.resourceFound,
|
||||
"matched_relationship": facts.matchedRelationship,
|
||||
"registry_overrode": facts.overriddenByRegistry,
|
||||
},
|
||||
Provenance: api.DecisionProvenance{
|
||||
Evaluator: "flex-auth/local",
|
||||
Mode: envelopeMode(ctx),
|
||||
PolicyPackage: e.policy.Metadata.ID,
|
||||
PolicyVersion: e.policy.Metadata.Version,
|
||||
PolicyPackageDigest: e.policy.Digest(),
|
||||
RegistrySnapshotDigest: e.store.Digest(),
|
||||
Caller: callerProvenance(ctx),
|
||||
},
|
||||
Caring: e.caringDecisionMetadata(facts.descriptor, expectation.ConformanceFindings),
|
||||
}
|
||||
api.CompleteDecision(&envelope, request, api.DecisionCompletion{
|
||||
AllowTTL: e.policy.Metadata.AllowTTL,
|
||||
Now: e.now(),
|
||||
})
|
||||
envelope.ID = decisionID(e.policy.Metadata, request, envelope)
|
||||
if envelope.Signature == nil {
|
||||
envelope.Signature = api.UnsignedEnvelopeSignature()
|
||||
}
|
||||
return envelope
|
||||
}
|
||||
|
||||
func callerProvenance(ctx context.Context) *api.CallerProvenance {
|
||||
record, ok := callerauth.RecordFromContext(ctx)
|
||||
if !ok {
|
||||
record = callerauth.Record{Mode: callerauth.ModeDisabled}
|
||||
}
|
||||
out := &api.CallerProvenance{Mode: string(record.Mode)}
|
||||
if record.Principal != "" {
|
||||
out.Principal = record.Principal
|
||||
out.Audience = record.Audience
|
||||
if !record.NotAfter.IsZero() {
|
||||
out.NotAfter = record.NotAfter.UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// recordDecisions releases no effect until its required record commits.
|
||||
// GH-DEC-2026-024 refuses the former restrictive-effect failure exception.
|
||||
// Failed decisions must not enter Explain's history as if they were released.
|
||||
func (e *Engine) recordDecisions(decisions []api.DecisionEnvelope) error {
|
||||
e.mu.RLock()
|
||||
log := e.log
|
||||
e.mu.RUnlock()
|
||||
if log != nil && len(decisions) != 0 {
|
||||
if err := appendAll(log, decisions); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrRecordNotCommitted, err)
|
||||
}
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, decision := range decisions {
|
||||
e.history[decision.ID] = decision
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func appendAll(log DecisionRecorder, decisions []api.DecisionEnvelope) error {
|
||||
if batch, ok := log.(BatchRecorder); ok {
|
||||
return batch.AppendBatch(decisions)
|
||||
}
|
||||
for _, decision := range decisions {
|
||||
if err := log.Append(decision); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) caringDecisionMetadata(descriptor *api.CaringAccessDescriptor, findings []api.CaringConformanceFinding) *api.CaringDecisionMetadata {
|
||||
profile := e.policy.Metadata.Caring.Profile
|
||||
if descriptor != nil && descriptor.Profile != "" {
|
||||
profile = descriptor.Profile
|
||||
}
|
||||
|
||||
metadata := &api.CaringDecisionMetadata{
|
||||
Profile: profile,
|
||||
ConformanceFindings: append([]api.CaringConformanceFinding(nil), findings...),
|
||||
}
|
||||
if descriptor == nil {
|
||||
metadata.ConformanceFindings = append(metadata.ConformanceFindings, api.CaringConformanceFinding{
|
||||
Code: "CARING-DESCRIPTOR-MISSING",
|
||||
Severity: "warning",
|
||||
Message: "no CARING descriptor matched the request",
|
||||
Fields: []string{"caring_context"},
|
||||
})
|
||||
return metadata
|
||||
}
|
||||
|
||||
descriptorCopy := *descriptor
|
||||
metadata.Descriptor = &descriptorCopy
|
||||
metadata.RestrictionsEvaluated = append([]api.Restriction(nil), descriptor.Restrictions...)
|
||||
metadata.ExposureModes = append([]api.ExposureMode(nil), descriptor.ExposureModes...)
|
||||
metadata.DerivedCapabilities = append([]api.CaringDerivedCapability(nil), descriptor.DerivedCapabilities...)
|
||||
return metadata
|
||||
}
|
||||
|
||||
func decisionID(metadata api.PolicyPackageMetadata, request api.CheckRequest, envelope api.DecisionEnvelope) string {
|
||||
data, _ := json.Marshal(struct {
|
||||
PolicyID string `json:"policy_id"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Request api.CheckRequest `json:"request"`
|
||||
Effect api.DecisionEffect `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}{
|
||||
PolicyID: metadata.ID,
|
||||
PolicyVersion: metadata.Version,
|
||||
Request: request,
|
||||
Effect: envelope.Effect,
|
||||
Reason: envelope.Reason,
|
||||
})
|
||||
sum := sha256.Sum256(data)
|
||||
return "decision:" + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
func copyMap(in map[string]any) map[string]any {
|
||||
out := make(map[string]any, len(in))
|
||||
for key, value := range in {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// setAuthoritative writes a registry fact over whatever the request carried for
|
||||
// that key, and records the key when a caller value was displaced so the
|
||||
// override is visible in diagnostics rather than silent.
|
||||
func setAuthoritative(target map[string]any, key string, value any, scope string, overridden *[]string) {
|
||||
if isEmptyAttribute(value) {
|
||||
return
|
||||
}
|
||||
if existing, exists := target[key]; exists && overridden != nil && !equalAttribute(existing, value) {
|
||||
*overridden = append(*overridden, scope+"."+key)
|
||||
}
|
||||
target[key] = value
|
||||
}
|
||||
|
||||
func setAuthoritatives(target map[string]any, attrs map[string]any, scope string, overridden *[]string) {
|
||||
for _, key := range sortedKeys(attrs) {
|
||||
setAuthoritative(target, key, attrs[key], scope, overridden)
|
||||
}
|
||||
}
|
||||
|
||||
func equalAttribute(a, b any) bool {
|
||||
left, errLeft := json.Marshal(a)
|
||||
right, errRight := json.Marshal(b)
|
||||
if errLeft != nil || errRight != nil {
|
||||
return false
|
||||
}
|
||||
return bytes.Equal(left, right)
|
||||
}
|
||||
|
||||
func sortedKeys(attrs map[string]any) []string {
|
||||
keys := make([]string, 0, len(attrs))
|
||||
for key := range attrs {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func addAttributes(target map[string]any, attrs map[string]any) {
|
||||
for key, value := range attrs {
|
||||
addAttribute(target, key, value)
|
||||
}
|
||||
}
|
||||
|
||||
func addAttribute(target map[string]any, key string, value any) {
|
||||
if isEmptyAttribute(value) {
|
||||
return
|
||||
}
|
||||
if _, exists := target[key]; !exists {
|
||||
target[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
func resourceMatchesFilters(resource api.ResourceRef, filters map[string]any) bool {
|
||||
for key, want := range filters {
|
||||
var got any
|
||||
switch key {
|
||||
case "id":
|
||||
got = resource.ID
|
||||
case "type", "resource_type":
|
||||
got = resource.Type
|
||||
case "system":
|
||||
got = resource.System
|
||||
case "tenant":
|
||||
got = resource.Tenant
|
||||
default:
|
||||
got = resource.Attributes[key]
|
||||
}
|
||||
if !valuesEqual(got, want) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func valuesEqual(got, want any) bool {
|
||||
if reflect.DeepEqual(got, want) {
|
||||
return true
|
||||
}
|
||||
return fmt.Sprint(got) == fmt.Sprint(want)
|
||||
}
|
||||
|
||||
func explanationSummary(decision api.DecisionEnvelope) string {
|
||||
action, _ := decision.Diagnostics["action"].(string)
|
||||
actor := decision.Subject.ID
|
||||
capability := action
|
||||
plane := ""
|
||||
if decision.Caring != nil && decision.Caring.Descriptor != nil {
|
||||
descriptor := decision.Caring.Descriptor
|
||||
if descriptor.OrganizationRelation != "" || descriptor.CanonicalRole != "" {
|
||||
actor = strings.TrimSpace(fmt.Sprintf("%s %s", descriptor.OrganizationRelation, descriptor.CanonicalRole))
|
||||
}
|
||||
if len(descriptor.Capabilities) > 0 {
|
||||
capability = string(descriptor.Capabilities[0])
|
||||
}
|
||||
if len(descriptor.Planes) > 0 {
|
||||
plane = string(descriptor.Planes[0]) + " Plane "
|
||||
}
|
||||
}
|
||||
if capability == "" {
|
||||
capability = "access"
|
||||
}
|
||||
|
||||
verb := "may"
|
||||
switch decision.Effect {
|
||||
case api.DecisionEffectDeny:
|
||||
verb = "may not"
|
||||
case api.DecisionEffectRedact:
|
||||
verb = "receives redacted"
|
||||
case api.DecisionEffectAuditOnly:
|
||||
verb = "is audit-only for"
|
||||
case api.DecisionEffectNotApplicable:
|
||||
verb = "has no applicable policy for"
|
||||
}
|
||||
|
||||
reason := decision.Reason
|
||||
if reason == "" {
|
||||
reason = string(decision.Effect)
|
||||
}
|
||||
return fmt.Sprintf("%s %s %s %sresource %s because %s.", actor, verb, capability, plane, decision.Resource.ID, reason)
|
||||
}
|
||||
|
||||
func isEmptyAttribute(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return typed == ""
|
||||
case api.OrganizationRelation:
|
||||
return typed == ""
|
||||
case []api.CanonicalRole:
|
||||
return len(typed) == 0
|
||||
case []string:
|
||||
return len(typed) == 0
|
||||
default:
|
||||
return value == nil
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package decision
|
||||
|
||||
import "context"
|
||||
|
||||
// LosslessJSONProfile is an explicit optional wire decoder profile for the
|
||||
// normal /v1/check handler. Legacy callers retain their original float64
|
||||
// projection. The canonical request and signature algorithms are unchanged.
|
||||
const LosslessJSONProfile = "lossless-json-v1"
|
||||
const losslessStandaloneMode = "standalone/lossless-json-v1"
|
||||
|
||||
type jsonProfileContextKey struct{}
|
||||
|
||||
// WithLosslessJSONProfile is called only by the producer after selecting its
|
||||
// UseNumber decoder. No request/body flag can install this context key. The
|
||||
// signed provenance mode authenticates which decoder produced the decision.
|
||||
func WithLosslessJSONProfile(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx,jsonProfileContextKey{},LosslessJSONProfile)
|
||||
}
|
||||
|
||||
func envelopeMode(ctx context.Context) string {
|
||||
if ctx.Value(jsonProfileContextKey{})==LosslessJSONProfile{return losslessStandaloneMode}
|
||||
return "standalone"
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
{
|
||||
"argv": [
|
||||
"/usr/bin/bwrap",
|
||||
"--unshare-net",
|
||||
"--unshare-pid",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--symlink",
|
||||
"usr/bin",
|
||||
"/bin",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--bind",
|
||||
"/tmp/apps-accessengine-adapter-tests-ulc9rfnf",
|
||||
"/work",
|
||||
"--ro-bind",
|
||||
"/tmp/forgejo-independent-r1/go",
|
||||
"/toolchain",
|
||||
"--chdir",
|
||||
"/work/adapter",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"PATH",
|
||||
"/toolchain/bin:/usr/bin:/bin",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work/home",
|
||||
"--setenv",
|
||||
"GOPROXY",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOSUMDB",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOTOOLCHAIN",
|
||||
"local",
|
||||
"--setenv",
|
||||
"GOCACHE",
|
||||
"/work/gocache",
|
||||
"--setenv",
|
||||
"GOMODCACHE",
|
||||
"/work/modules",
|
||||
"--setenv",
|
||||
"CGO_ENABLED",
|
||||
"0",
|
||||
"--",
|
||||
"go",
|
||||
"test",
|
||||
"-json",
|
||||
"./..."
|
||||
],
|
||||
"returncode": 0,
|
||||
"workspace": "/tmp/apps-accessengine-adapter-tests-ulc9rfnf",
|
||||
"seconds": 80.62,
|
||||
"all_owned_processes_terminal": true
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
{"Time":"2026-10-17T22:09:50.144492174Z","Action":"start","Package":"github.com/netkingdom/access-engine/internal/sign"}
|
||||
{"Time":"2026-10-17T22:09:50.144675372Z","Action":"output","Package":"github.com/netkingdom/access-engine/internal/sign","Output":"? \tgithub.com/netkingdom/access-engine/internal/sign\t[no test files]\n"}
|
||||
{"Time":"2026-10-17T22:09:50.144706304Z","Action":"skip","Package":"github.com/netkingdom/access-engine/internal/sign","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:09:50.145835212Z","Action":"start","Package":"github.com/netkingdom/access-engine/pkg/api"}
|
||||
{"Time":"2026-10-17T22:09:50.145926678Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/api","Output":"? \tgithub.com/netkingdom/access-engine/pkg/api\t[no test files]\n"}
|
||||
{"Time":"2026-10-17T22:09:50.145957023Z","Action":"skip","Package":"github.com/netkingdom/access-engine/pkg/api","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.39043884Z","Action":"start","Package":"github.com/netkingdom/access-engine/pkg/decisionpep"}
|
||||
{"Time":"2026-10-17T22:10:24.429608779Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision"}
|
||||
{"Time":"2026-10-17T22:10:24.429697306Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision","Output":"=== RUN TestAuthenticDecisionProducerCanonicalPrecision\n"}
|
||||
{"Time":"2026-10-17T22:10:24.480861819Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision","Output":"--- PASS: TestAuthenticDecisionProducerCanonicalPrecision (0.05s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.480957739Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision","Elapsed":0.05}
|
||||
{"Time":"2026-10-17T22:10:24.480986219Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings"}
|
||||
{"Time":"2026-10-17T22:10:24.48099736Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings","Output":"=== RUN TestDecisionAdverseBindings\n"}
|
||||
{"Time":"2026-10-17T22:10:24.481011265Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned"}
|
||||
{"Time":"2026-10-17T22:10:24.481023048Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned","Output":"=== RUN TestDecisionAdverseBindings/unsigned\n"}
|
||||
{"Time":"2026-10-17T22:10:24.499929273Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned","Output":"--- PASS: TestDecisionAdverseBindings/unsigned (0.02s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.506424097Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned","Elapsed":0.02}
|
||||
{"Time":"2026-10-17T22:10:24.506504597Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy"}
|
||||
{"Time":"2026-10-17T22:10:24.506519273Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy","Output":"=== RUN TestDecisionAdverseBindings/policy\n"}
|
||||
{"Time":"2026-10-17T22:10:24.506538064Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy","Output":"--- PASS: TestDecisionAdverseBindings/policy (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.506777892Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.510069098Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry"}
|
||||
{"Time":"2026-10-17T22:10:24.510157441Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry","Output":"=== RUN TestDecisionAdverseBindings/registry\n"}
|
||||
{"Time":"2026-10-17T22:10:24.5171087Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry","Output":"--- PASS: TestDecisionAdverseBindings/registry (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.517188309Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.517207605Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context"}
|
||||
{"Time":"2026-10-17T22:10:24.517218791Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context","Output":"=== RUN TestDecisionAdverseBindings/context\n"}
|
||||
{"Time":"2026-10-17T22:10:24.517232752Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context","Output":"--- PASS: TestDecisionAdverseBindings/context (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.517244406Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.517255235Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal"}
|
||||
{"Time":"2026-10-17T22:10:24.517272363Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal","Output":"=== RUN TestDecisionAdverseBindings/caller-principal\n"}
|
||||
{"Time":"2026-10-17T22:10:24.523279401Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal","Output":"--- PASS: TestDecisionAdverseBindings/caller-principal (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.5233947Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.523423924Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision"}
|
||||
{"Time":"2026-10-17T22:10:24.523436075Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision","Output":"=== RUN TestDecisionAdverseBindings/stale-decision\n"}
|
||||
{"Time":"2026-10-17T22:10:24.534074839Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision","Output":"--- PASS: TestDecisionAdverseBindings/stale-decision (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.53416231Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.534184783Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry"}
|
||||
{"Time":"2026-10-17T22:10:24.534200442Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry","Output":"=== RUN TestDecisionAdverseBindings/subnanosecond-expiry\n"}
|
||||
{"Time":"2026-10-17T22:10:24.538151599Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry","Output":"--- PASS: TestDecisionAdverseBindings/subnanosecond-expiry (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.544175968Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.544297696Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL"}
|
||||
{"Time":"2026-10-17T22:10:24.544368993Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL","Output":"=== RUN TestDecisionAdverseBindings/excess-TTL\n"}
|
||||
{"Time":"2026-10-17T22:10:24.551493071Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL","Output":"--- PASS: TestDecisionAdverseBindings/excess-TTL (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.560914567Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.560989023Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor"}
|
||||
{"Time":"2026-10-17T22:10:24.561003314Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor","Output":"=== RUN TestDecisionAdverseBindings/actor\n"}
|
||||
{"Time":"2026-10-17T22:10:24.561023859Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor","Output":"--- PASS: TestDecisionAdverseBindings/actor (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.561036184Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.561054231Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action"}
|
||||
{"Time":"2026-10-17T22:10:24.561063498Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action","Output":"=== RUN TestDecisionAdverseBindings/action\n"}
|
||||
{"Time":"2026-10-17T22:10:24.572375026Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action","Output":"--- PASS: TestDecisionAdverseBindings/action (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.572450924Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.572467244Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired"}
|
||||
{"Time":"2026-10-17T22:10:24.572477402Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired","Output":"=== RUN TestDecisionAdverseBindings/caller-expired\n"}
|
||||
{"Time":"2026-10-17T22:10:24.577182575Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired","Output":"--- PASS: TestDecisionAdverseBindings/caller-expired (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.582558772Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.582654508Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL"}
|
||||
{"Time":"2026-10-17T22:10:24.582689565Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL","Output":"=== RUN TestDecisionAdverseBindings/missing-TTL\n"}
|
||||
{"Time":"2026-10-17T22:10:24.585194646Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL","Output":"--- PASS: TestDecisionAdverseBindings/missing-TTL (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.592760753Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.592878642Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation"}
|
||||
{"Time":"2026-10-17T22:10:24.592927934Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation","Output":"=== RUN TestDecisionAdverseBindings/obligation\n"}
|
||||
{"Time":"2026-10-17T22:10:24.592959481Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation","Output":"--- PASS: TestDecisionAdverseBindings/obligation (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.592973717Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.592985353Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator"}
|
||||
{"Time":"2026-10-17T22:10:24.592994538Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator","Output":"=== RUN TestDecisionAdverseBindings/evaluator\n"}
|
||||
{"Time":"2026-10-17T22:10:24.601946141Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator","Output":"--- PASS: TestDecisionAdverseBindings/evaluator (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.603248446Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.603322701Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant"}
|
||||
{"Time":"2026-10-17T22:10:24.603337001Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant","Output":"=== RUN TestDecisionAdverseBindings/tenant\n"}
|
||||
{"Time":"2026-10-17T22:10:24.612712934Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant","Output":"--- PASS: TestDecisionAdverseBindings/tenant (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.612884973Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.612920681Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource"}
|
||||
{"Time":"2026-10-17T22:10:24.612933392Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource","Output":"=== RUN TestDecisionAdverseBindings/resource\n"}
|
||||
{"Time":"2026-10-17T22:10:24.621044935Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource","Output":"--- PASS: TestDecisionAdverseBindings/resource (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.628997607Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.629080522Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience"}
|
||||
{"Time":"2026-10-17T22:10:24.629094372Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience","Output":"=== RUN TestDecisionAdverseBindings/caller-audience\n"}
|
||||
{"Time":"2026-10-17T22:10:24.629117112Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience","Output":"--- PASS: TestDecisionAdverseBindings/caller-audience (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.630735456Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.631411149Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin"}
|
||||
{"Time":"2026-10-17T22:10:24.631577889Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin","Output":"=== RUN TestDecisionAdverseBindings/future-begin\n"}
|
||||
{"Time":"2026-10-17T22:10:24.657036421Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin","Output":"--- PASS: TestDecisionAdverseBindings/future-begin (0.02s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.657116489Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin","Elapsed":0.02}
|
||||
{"Time":"2026-10-17T22:10:24.657143941Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect"}
|
||||
{"Time":"2026-10-17T22:10:24.657158332Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect","Output":"=== RUN TestDecisionAdverseBindings/effect\n"}
|
||||
{"Time":"2026-10-17T22:10:24.657175911Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect","Output":"--- PASS: TestDecisionAdverseBindings/effect (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.65718999Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.65720407Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version"}
|
||||
{"Time":"2026-10-17T22:10:24.657214613Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version","Output":"=== RUN TestDecisionAdverseBindings/version\n"}
|
||||
{"Time":"2026-10-17T22:10:24.666404636Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version","Output":"--- PASS: TestDecisionAdverseBindings/version (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.669141647Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.676572732Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest"}
|
||||
{"Time":"2026-10-17T22:10:24.676661544Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest","Output":"=== RUN TestDecisionAdverseBindings/policy-digest\n"}
|
||||
{"Time":"2026-10-17T22:10:24.697150696Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest","Output":"--- PASS: TestDecisionAdverseBindings/policy-digest (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.697229212Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.697252715Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose"}
|
||||
{"Time":"2026-10-17T22:10:24.697263929Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose","Output":"=== RUN TestDecisionAdverseBindings/purpose\n"}
|
||||
{"Time":"2026-10-17T22:10:24.705135118Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose","Output":"--- PASS: TestDecisionAdverseBindings/purpose (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.705482719Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.705552427Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted"}
|
||||
{"Time":"2026-10-17T22:10:24.705569134Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted","Output":"=== RUN TestDecisionAdverseBindings/submitted\n"}
|
||||
{"Time":"2026-10-17T22:10:24.705588485Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted","Output":"--- PASS: TestDecisionAdverseBindings/submitted (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.705609471Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.705623192Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn"}
|
||||
{"Time":"2026-10-17T22:10:24.7056338Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn","Output":"=== RUN TestDecisionAdverseBindings/caller-warn\n"}
|
||||
{"Time":"2026-10-17T22:10:24.719064773Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn","Output":"--- PASS: TestDecisionAdverseBindings/caller-warn (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.719147917Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.71918009Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired"}
|
||||
{"Time":"2026-10-17T22:10:24.719195786Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired","Output":"=== RUN TestDecisionAdverseBindings/expired\n"}
|
||||
{"Time":"2026-10-17T22:10:24.731508113Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired","Output":"--- PASS: TestDecisionAdverseBindings/expired (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.731662151Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.731694442Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings","Output":"--- PASS: TestDecisionAdverseBindings (0.25s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.731749575Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings","Elapsed":0.25}
|
||||
{"Time":"2026-10-17T22:10:24.731770644Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay"}
|
||||
{"Time":"2026-10-17T22:10:24.731782905Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay","Output":"=== RUN TestSignatureForgeryAndReplay\n"}
|
||||
{"Time":"2026-10-17T22:10:24.731859722Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload"}
|
||||
{"Time":"2026-10-17T22:10:24.731873985Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload","Output":"=== RUN TestSignatureForgeryAndReplay/forged-payload\n"}
|
||||
{"Time":"2026-10-17T22:10:24.7559722Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload","Output":"--- PASS: TestSignatureForgeryAndReplay/forged-payload (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756050321Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.756086773Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key"}
|
||||
{"Time":"2026-10-17T22:10:24.756098106Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key","Output":"=== RUN TestSignatureForgeryAndReplay/wrong-key\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756121177Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key","Output":"--- PASS: TestSignatureForgeryAndReplay/wrong-key (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.75613319Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.75614422Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay"}
|
||||
{"Time":"2026-10-17T22:10:24.75615266Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay","Output":"=== RUN TestSignatureForgeryAndReplay/replay\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756164168Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay","Output":"--- PASS: TestSignatureForgeryAndReplay/replay (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756174657Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:10:24.756187873Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay","Output":"--- PASS: TestSignatureForgeryAndReplay (0.02s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756199188Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay","Elapsed":0.02}
|
||||
{"Time":"2026-10-17T22:10:24.756209851Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse"}
|
||||
{"Time":"2026-10-17T22:10:24.756218769Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse","Output":"=== RUN TestUnavailableAndPublicTokenFileRefuse\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756229973Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse","Output":"--- PASS: TestUnavailableAndPublicTokenFileRefuse (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:10:24.756239929Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:10:24.756252879Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Output":"PASS\n"}
|
||||
{"Time":"2026-10-17T22:10:24.760181613Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Output":"ok \tgithub.com/netkingdom/access-engine/pkg/decisionpep\t0.369s\n"}
|
||||
{"Time":"2026-10-17T22:10:24.807268555Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Elapsed":0.417}
|
||||
|
|
@ -0,0 +1,291 @@
|
|||
// Package decisionpep authenticates the producer's decision record for one
|
||||
// current request. It never evaluates policy, caches a verdict, or discovers trust.
|
||||
package decisionpep
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
var ErrRefused = errors.New("authenticated decision refused")
|
||||
|
||||
const nonceKey = "decisionpep_request_nonce"
|
||||
const maxBytes = 2 << 20
|
||||
|
||||
// Admission is public, independently admitted owner configuration. TokenFile is
|
||||
// only a path to a private rotating caller credential, never a literal token.
|
||||
type Admission struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
CAFile string `json:"ca_file"`
|
||||
TokenFile string `json:"token_file"`
|
||||
Keys map[string]string `json:"keys"`
|
||||
Evaluator string `json:"evaluator"`
|
||||
PolicyPackage string `json:"policy_package"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
PolicyDigest string `json:"policy_digest"`
|
||||
RegistryDigest string `json:"registry_digest"`
|
||||
CallerPrincipal string `json:"caller_principal"`
|
||||
CallerAudience string `json:"caller_audience"`
|
||||
MaxTTL string `json:"max_ttl"`
|
||||
MaxClockSkew string `json:"max_clock_skew"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
admission Admission
|
||||
keys map[string]ed25519.PublicKey
|
||||
http *http.Client
|
||||
maxTTL, skew time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// Load reads a current independently admitted file. No trust is bootstrapped
|
||||
// from a PDP response, token contents, discovery endpoint, or environment value.
|
||||
func Load(path string) (*Client, error) {
|
||||
raw, err := readFile(path, false)
|
||||
if err != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
var a Admission
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&a) != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if _, err = d.Token(); err != io.EOF {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
return New(a)
|
||||
}
|
||||
|
||||
func New(a Admission) (*Client, error) {
|
||||
u, err := url.Parse(a.Endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "/v1/check" || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if !filepath.IsAbs(a.CAFile) || !filepath.IsAbs(a.TokenFile) || a.Evaluator == "" || a.PolicyPackage == "" || a.PolicyVersion == "" || a.CallerPrincipal == "" || a.CallerAudience == "" {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if !validDigest(a.PolicyDigest) || !validDigest(a.RegistryDigest) || len(a.Keys) == 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
ttl, err := time.ParseDuration(a.MaxTTL)
|
||||
if err != nil || ttl <= 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
skew, err := time.ParseDuration(a.MaxClockSkew)
|
||||
if err != nil || skew < 0 || skew > ttl {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
ca, err := readFile(a.CAFile, false)
|
||||
if err != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
keys := map[string]ed25519.PublicKey{}
|
||||
for kid, value := range a.Keys {
|
||||
b, e := base64.RawURLEncoding.Strict().DecodeString(value)
|
||||
if e != nil || kid == "" || len(b) != ed25519.PublicKeySize {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
keys[kid] = append(ed25519.PublicKey(nil), b...)
|
||||
}
|
||||
transport := &http.Transport{Proxy: nil, TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}, DisableKeepAlives: true}
|
||||
client := &http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return ErrRefused }}
|
||||
return &Client{admission: a, keys: keys, http: client, maxTTL: ttl, skew: skew, now: time.Now}, nil
|
||||
}
|
||||
|
||||
func validDigest(value string) bool {
|
||||
if !strings.HasPrefix(value, "sha256:") || len(value) != 71 {
|
||||
return false
|
||||
}
|
||||
_, e := hex.DecodeString(value[7:])
|
||||
return e == nil && strings.ToLower(value) == value
|
||||
}
|
||||
|
||||
func readFile(path string, private bool) ([]byte, error) {
|
||||
if !filepath.IsAbs(path) {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
f, e := os.Open(path)
|
||||
if e != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
defer f.Close()
|
||||
info, e := f.Stat()
|
||||
if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0022 != 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if private && info.Mode().Perm()&0007 != 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
b, e := io.ReadAll(io.LimitReader(f, maxBytes+1))
|
||||
if e != nil || len(b) > maxBytes {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Check sends exactly one request with a cryptographically fresh nonce. The
|
||||
// returned envelope is the producer's authenticated typed interpretation.
|
||||
// Callers must execute only the request's exact operation and honor their own
|
||||
// execution boundary; a login decision is never a later resource decision.
|
||||
func (c *Client) Check(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
refuse := func() (api.DecisionEnvelope, error) { return api.DecisionEnvelope{}, ErrRefused }
|
||||
if c == nil || request.Purpose != "" || request.Tenant == "" || request.Subject.ID == "" || request.Subject.Type == "" || request.Resource.ID == "" || request.Resource.Type == "" || request.Resource.System == "" || request.Action == "" {
|
||||
return refuse()
|
||||
}
|
||||
if request.Subject.Tenant != request.Tenant || request.Resource.Tenant != request.Tenant {
|
||||
return refuse()
|
||||
}
|
||||
if request.PolicyVersion != "" && request.PolicyVersion != c.admission.PolicyVersion {
|
||||
return refuse()
|
||||
}
|
||||
// Use the producer's typed representation and preserve numeric lexemes. A
|
||||
// producer that rounds before hashing fails this join rather than weakening it.
|
||||
raw, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&request) != nil {
|
||||
return refuse()
|
||||
}
|
||||
if request.Context == nil {
|
||||
request.Context = map[string]any{}
|
||||
}
|
||||
if _, exists := request.Context[nonceKey]; exists {
|
||||
return refuse()
|
||||
}
|
||||
nonce := make([]byte, 32)
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
return refuse()
|
||||
}
|
||||
request.Context[nonceKey] = hex.EncodeToString(nonce)
|
||||
request.ID = hex.EncodeToString(nonce)
|
||||
request.PolicyVersion = c.admission.PolicyVersion
|
||||
raw, err = json.Marshal(request)
|
||||
if err != nil || len(raw) > maxBytes {
|
||||
return refuse()
|
||||
}
|
||||
token, err := readFile(c.admission.TokenFile, true)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
value := strings.TrimSpace(string(token))
|
||||
if value == "" || strings.ContainsAny(value, " \t\r\n") {
|
||||
return refuse()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.admission.Endpoint, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+value)
|
||||
started := c.now().UTC()
|
||||
response, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return refuse()
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxBytes+1))
|
||||
if err != nil || len(body) > maxBytes {
|
||||
return refuse()
|
||||
}
|
||||
envelope, err := sign.DecodeEnvelope(body)
|
||||
if err != nil || sign.Verify(envelope, c.keys) != nil {
|
||||
return refuse()
|
||||
}
|
||||
if c.validate(envelope, request, started, c.now().UTC()) != nil {
|
||||
return refuse()
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
func (c *Client) validate(e api.DecisionEnvelope, r api.CheckRequest, started, now time.Time) error {
|
||||
p := e.Provenance
|
||||
b := e.Binding
|
||||
l := e.Lifetime
|
||||
if e.ID == "" || e.ContractVersion != api.DecisionRecordContractV1 || e.Effect != api.DecisionEffectAllow || e.RequestID != r.ID || len(e.Obligations) != 0 || b == nil || l == nil {
|
||||
return ErrRefused
|
||||
}
|
||||
if p.Evaluator != c.admission.Evaluator || p.Mode != "standalone" || p.PolicyPackage != c.admission.PolicyPackage || p.PolicyVersion != c.admission.PolicyVersion || p.PolicyPackageDigest != c.admission.PolicyDigest || p.RegistrySnapshotDigest != c.admission.RegistryDigest || e.MatchedPolicyVersion != p.PolicyVersion {
|
||||
return ErrRefused
|
||||
}
|
||||
if b.Purpose != "" || b.SubmittedRequestDigest != api.RequestDigest(r) || b.Tenant != r.Tenant || b.Action != r.Action || api.CanonicalDigest(b.Context) != api.CanonicalDigest(r.Context) {
|
||||
return ErrRefused
|
||||
}
|
||||
if !sameSubject(b.Subject, r.Subject) || !sameResource(b.Resource, r.Resource) || !sameSubject(e.Subject, b.Subject) || !sameResource(e.Resource, b.Resource) {
|
||||
return ErrRefused
|
||||
}
|
||||
evaluated := api.CheckRequest{Tenant: b.Tenant, Subject: b.Subject, Action: b.Action, Resource: b.Resource, Context: b.Context, Purpose: b.Purpose}
|
||||
if b.RequestDigest != api.RequestDigest(evaluated) {
|
||||
return ErrRefused
|
||||
}
|
||||
for k, v := range api.InputClaimDigests(r) {
|
||||
if p.InputClaimDigests[k] != v {
|
||||
return ErrRefused
|
||||
}
|
||||
}
|
||||
caller := p.Caller
|
||||
if caller == nil || caller.Mode != "enforce" || caller.Principal != c.admission.CallerPrincipal || caller.Audience != c.admission.CallerAudience {
|
||||
return ErrRefused
|
||||
}
|
||||
callerEnd, err := time.Parse(time.RFC3339Nano, caller.NotAfter)
|
||||
if err != nil || !now.Before(callerEnd) {
|
||||
return ErrRefused
|
||||
}
|
||||
decision, err := time.Parse(time.RFC3339Nano, p.DecisionTime)
|
||||
if err != nil || decision.Before(started.Add(-c.skew)) || decision.After(now.Add(c.skew)) {
|
||||
return ErrRefused
|
||||
}
|
||||
begin, err := time.Parse(time.RFC3339Nano, l.NotBefore)
|
||||
if err != nil || begin.After(now) {
|
||||
return ErrRefused
|
||||
}
|
||||
end, err := time.Parse(time.RFC3339Nano, l.ExpiresAt)
|
||||
if err != nil || !now.Before(end) || !end.After(begin) || end.Sub(begin) > c.maxTTL || end.After(callerEnd) {
|
||||
return ErrRefused
|
||||
}
|
||||
ttl, err := time.ParseDuration(l.TTL)
|
||||
if err != nil || l.Kind != api.DecisionLifetimeTTL || ttl <= 0 || ttl > c.maxTTL {
|
||||
return ErrRefused
|
||||
}
|
||||
// Producer CompleteDecision uses its exact decision instant for both bounds.
|
||||
// RFC3339 output can truncate subsecond precision, so do not invent lost time.
|
||||
if !begin.Equal(decision) || end.Sub(begin) != ttl {
|
||||
return ErrRefused
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameSubject(a, b api.SubjectRef) bool {
|
||||
return a.ID == b.ID && a.Type == b.Type && a.Tenant == b.Tenant
|
||||
}
|
||||
func sameResource(a, b api.ResourceRef) bool {
|
||||
return a.ID == b.ID && a.Type == b.Type && a.System == b.System && a.Tenant == b.Tenant
|
||||
}
|
||||
|
|
@ -0,0 +1,207 @@
|
|||
package decisionpep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
type transportFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func testClient(t *testing.T) (*Client, ed25519.PrivateKey, time.Time) {
|
||||
t.Helper()
|
||||
pub, key, e := ed25519.GenerateKey(rand.Reader)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
now := time.Date(2026, 10, 18, 1, 2, 3, 0, time.UTC)
|
||||
dir := t.TempDir()
|
||||
cert, e := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}, &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}, pub, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ca := filepath.Join(dir, "ca.pem")
|
||||
token := filepath.Join(dir, "token")
|
||||
if e = os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0600); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = os.WriteFile(token, []byte("synthetic-caller-token"), 0600); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a := Admission{Endpoint: "https://pdp.invalid/v1/check", CAFile: ca, TokenFile: token, Keys: map[string]string{"test-key": base64.RawURLEncoding.EncodeToString(pub)}, Evaluator: "flex-auth/local", PolicyPackage: "forgejo.application-access", PolicyVersion: "v1", PolicyDigest: "sha256:" + strings.Repeat("1", 64), RegistryDigest: "sha256:" + strings.Repeat("2", 64), CallerPrincipal: "system:serviceaccount:test:forgejo", CallerAudience: "access-engine", MaxTTL: "30s", MaxClockSkew: "1s"}
|
||||
c, e := New(a)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.now = func() time.Time { return now }
|
||||
return c, key, now
|
||||
}
|
||||
func testRequest() api.CheckRequest {
|
||||
return api.CheckRequest{Tenant: "tenant:test", Subject: api.SubjectRef{ID: "subject:test", Type: api.SubjectType("Human"), Tenant: "tenant:test", Attributes: map[string]any{"groups": []string{"engineers"}}}, Action: "application.access", Resource: api.ResourceRef{ID: "application:forgejo", Type: "application", System: "forgejo", Tenant: "tenant:test"}, Context: map[string]any{"big": json.Number("9007199254740993"), "fraction": json.Number("0.123456789123456789")}}
|
||||
}
|
||||
func envelope(c *Client, r api.CheckRequest, key ed25519.PrivateKey, now time.Time) api.DecisionEnvelope {
|
||||
e := api.DecisionEnvelope{ID: "test-decision", RequestID: r.ID, Effect: api.DecisionEffectAllow, MatchedPolicyVersion: c.admission.PolicyVersion, Subject: r.Subject, Resource: r.Resource, Binding: api.NewDecisionBindingFor(r, r), Provenance: api.DecisionProvenance{Evaluator: c.admission.Evaluator, Mode: "standalone", PolicyPackage: c.admission.PolicyPackage, PolicyVersion: c.admission.PolicyVersion, PolicyPackageDigest: c.admission.PolicyDigest, RegistrySnapshotDigest: c.admission.RegistryDigest, Caller: &api.CallerProvenance{Mode: "enforce", Principal: c.admission.CallerPrincipal, Audience: c.admission.CallerAudience, NotAfter: now.Add(time.Minute).Format(time.RFC3339Nano)}}}
|
||||
api.CompleteDecision(&e, r, api.DecisionCompletion{AllowTTL: "10s", Now: now})
|
||||
if sign.Sign(&e, key, "test-key") != nil {
|
||||
panic("test sign")
|
||||
}
|
||||
return e
|
||||
}
|
||||
func respond(t *testing.T, c *Client, key ed25519.PrivateKey, now time.Time, mutate func(*api.DecisionEnvelope), resign bool) {
|
||||
t.Helper()
|
||||
c.http = &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if req.Header.Get("Authorization") != "Bearer synthetic-caller-token" {
|
||||
t.Fatal("wrong synthetic caller token")
|
||||
}
|
||||
var r api.CheckRequest
|
||||
d := json.NewDecoder(req.Body)
|
||||
d.UseNumber()
|
||||
if d.Decode(&r) != nil {
|
||||
t.Fatal("request decode")
|
||||
}
|
||||
if r.Context["big"] != json.Number("9007199254740993") || r.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("request numeric precision lost")
|
||||
}
|
||||
if len(r.Context[nonceKey].(string)) != 64 || r.ID != r.Context[nonceKey] {
|
||||
t.Fatal("nonce")
|
||||
}
|
||||
e := envelope(c, r, key, now)
|
||||
if mutate != nil {
|
||||
mutate(&e)
|
||||
}
|
||||
if resign {
|
||||
if sign.Sign(&e, key, "test-key") != nil {
|
||||
t.Fatal("sign")
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(b))), Header: http.Header{}}, nil
|
||||
})}
|
||||
}
|
||||
func TestAuthenticDecisionProducerCanonicalPrecision(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, nil, false)
|
||||
e, err := c.Check(context.Background(), testRequest())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.Binding.Context["big"] != json.Number("9007199254740993") || e.Binding.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("signed typed precision lost")
|
||||
}
|
||||
if sign.Verify(e, c.keys) != nil {
|
||||
t.Fatal("returned envelope not authentic producer bytes")
|
||||
}
|
||||
}
|
||||
func TestDecisionAdverseBindings(t *testing.T) {
|
||||
cases := map[string]func(*api.DecisionEnvelope){
|
||||
"unsigned": func(e *api.DecisionEnvelope) { e.Signature = api.UnsignedEnvelopeSignature() },
|
||||
"effect": func(e *api.DecisionEnvelope) { e.Effect = api.DecisionEffectDeny },
|
||||
"evaluator": func(e *api.DecisionEnvelope) { e.Provenance.Evaluator = "impostor" },
|
||||
"policy": func(e *api.DecisionEnvelope) { e.Provenance.PolicyPackage = "other" },
|
||||
"version": func(e *api.DecisionEnvelope) { e.Provenance.PolicyVersion = "v2" },
|
||||
"policy-digest": func(e *api.DecisionEnvelope) { e.Provenance.PolicyPackageDigest = "sha256:" + strings.Repeat("3", 64) },
|
||||
"registry": func(e *api.DecisionEnvelope) {
|
||||
e.Provenance.RegistrySnapshotDigest = "sha256:" + strings.Repeat("4", 64)
|
||||
},
|
||||
"tenant": func(e *api.DecisionEnvelope) { e.Binding.Tenant = "other" },
|
||||
"actor": func(e *api.DecisionEnvelope) { e.Binding.Subject.ID = "other" },
|
||||
"action": func(e *api.DecisionEnvelope) { e.Binding.Action = "write" },
|
||||
"resource": func(e *api.DecisionEnvelope) { e.Binding.Resource.ID = "other" },
|
||||
"purpose": func(e *api.DecisionEnvelope) { e.Binding.Purpose = "readback" },
|
||||
"submitted": func(e *api.DecisionEnvelope) { e.Binding.SubmittedRequestDigest = "wrong" },
|
||||
"context": func(e *api.DecisionEnvelope) { e.Binding.Context["fraction"] = json.Number("0.123456789123456788") },
|
||||
"caller-warn": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Mode = "warn" },
|
||||
"caller-principal": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Principal = "other" },
|
||||
"caller-audience": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Audience = "other" },
|
||||
"caller-expired": func(e *api.DecisionEnvelope) { e.Provenance.Caller.NotAfter = "2020-01-01T00:00:00Z" },
|
||||
"stale-decision": func(e *api.DecisionEnvelope) { e.Provenance.DecisionTime = "2020-01-01T00:00:00Z" },
|
||||
"expired": func(e *api.DecisionEnvelope) { e.Lifetime.ExpiresAt = "2020-01-01T00:00:00Z" },
|
||||
"future-begin": func(e *api.DecisionEnvelope) { e.Lifetime.NotBefore = "2030-01-01T00:00:00Z" },
|
||||
"subnanosecond-expiry": func(e *api.DecisionEnvelope) { e.Lifetime.ExpiresAt = "2026-10-18T01:02:02.999999999Z" },
|
||||
"missing-TTL": func(e *api.DecisionEnvelope) { e.Lifetime = nil },
|
||||
"excess-TTL": func(e *api.DecisionEnvelope) { e.Lifetime.TTL = "1h" },
|
||||
"obligation": func(e *api.DecisionEnvelope) { e.Obligations = []api.Obligation{{Type: "unimplemented"}} },
|
||||
}
|
||||
for name, mutation := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, mutation, name != "unsigned")
|
||||
if _, err := c.Check(context.Background(), testRequest()); err == nil {
|
||||
t.Fatal("accepted wrong signed binding")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestSignatureForgeryAndReplay(t *testing.T) {
|
||||
t.Run("forged-payload", func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, func(e *api.DecisionEnvelope) { e.Reason = "changed after signature" }, false)
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("forgery accepted")
|
||||
}
|
||||
})
|
||||
t.Run("wrong-key", func(t *testing.T) {
|
||||
c, _, now := testClient(t)
|
||||
_, key, _ := ed25519.GenerateKey(rand.Reader)
|
||||
respond(t, c, key, now, nil, false)
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("wrong key accepted")
|
||||
}
|
||||
})
|
||||
t.Run("replay", func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
var saved []byte
|
||||
c.http = &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if saved == nil {
|
||||
var r api.CheckRequest
|
||||
d := json.NewDecoder(req.Body)
|
||||
d.UseNumber()
|
||||
if d.Decode(&r) != nil {
|
||||
t.Fatal("decode")
|
||||
}
|
||||
e := envelope(c, r, key, now)
|
||||
saved, _ = json.Marshal(e)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(saved)))}, nil
|
||||
})}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("old decision replay accepted for new nonce")
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestUnavailableAndPublicTokenFileRefuse(t *testing.T) {
|
||||
c, _, _ := testClient(t)
|
||||
c.http = &http.Client{Transport: transportFunc(func(*http.Request) (*http.Response, error) { return nil, io.ErrUnexpectedEOF })}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("unavailable allowed")
|
||||
}
|
||||
if e := os.Chmod(c.admission.TokenFile, 0644); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("public token file allowed")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
{
|
||||
"state": "running",
|
||||
"pid": 4,
|
||||
"workspace": "/tmp/apps-pdp-forgejo-actual-bs7nxdhk",
|
||||
"argv": [
|
||||
"/usr/bin/bwrap",
|
||||
"--unshare-net",
|
||||
"--unshare-pid",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--symlink",
|
||||
"usr/bin",
|
||||
"/bin",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--bind",
|
||||
"/tmp/apps-pdp-forgejo-actual-bs7nxdhk",
|
||||
"/work",
|
||||
"--ro-bind",
|
||||
"/tmp/forgejo-independent-r1/go",
|
||||
"/toolchain",
|
||||
"--ro-bind",
|
||||
"/tmp/forgejo-independent-r1/gomodcache",
|
||||
"/modules",
|
||||
"--bind",
|
||||
"/tmp/apps-accessengine-adapter-tests-ulc9rfnf/gocache",
|
||||
"/adapter-cache",
|
||||
"--chdir",
|
||||
"/work/source",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"PATH",
|
||||
"/toolchain/bin:/usr/bin:/bin",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work/home",
|
||||
"--setenv",
|
||||
"GOPROXY",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOSUMDB",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOTOOLCHAIN",
|
||||
"local",
|
||||
"--setenv",
|
||||
"GOCACHE",
|
||||
"/adapter-cache",
|
||||
"--setenv",
|
||||
"GOMODCACHE",
|
||||
"/modules",
|
||||
"--setenv",
|
||||
"GOMAXPROCS",
|
||||
"4",
|
||||
"--setenv",
|
||||
"CGO_ENABLED",
|
||||
"1",
|
||||
"--",
|
||||
"go",
|
||||
"test",
|
||||
"-p",
|
||||
"4",
|
||||
"-json",
|
||||
"-tags",
|
||||
"sqlite sqlite_unlock_notify",
|
||||
"./services/auth/source/oauth2",
|
||||
"-run",
|
||||
"TestVerifiedApplicationIdentityActualJOSE|TestRequired|TestCurrent",
|
||||
"-count=1"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,261 @@
|
|||
module forgejo.org
|
||||
|
||||
go 1.24
|
||||
|
||||
toolchain go1.24.3
|
||||
|
||||
require (
|
||||
code.forgejo.org/f3/gof3/v3 v3.10.6
|
||||
code.forgejo.org/forgejo-contrib/go-libravatar v0.0.0-20191008002943-06d1c002b251
|
||||
code.forgejo.org/forgejo/levelqueue v1.0.0
|
||||
code.forgejo.org/forgejo/reply v1.0.2
|
||||
code.forgejo.org/go-chi/binding v1.0.0
|
||||
code.forgejo.org/go-chi/cache v1.0.0
|
||||
code.forgejo.org/go-chi/captcha v1.0.1
|
||||
code.forgejo.org/go-chi/session v1.0.1
|
||||
code.gitea.io/actions-proto-go v0.4.0
|
||||
code.gitea.io/sdk/gitea v0.20.0
|
||||
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570
|
||||
connectrpc.com/connect v1.17.0
|
||||
github.com/42wim/httpsig v1.2.2
|
||||
github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358
|
||||
github.com/ProtonMail/go-crypto v1.1.6
|
||||
github.com/PuerkitoBio/goquery v1.10.2
|
||||
github.com/SaveTheRbtz/zstd-seekable-format-go/pkg v0.7.2
|
||||
github.com/alecthomas/chroma/v2 v2.15.0
|
||||
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb
|
||||
github.com/blevesearch/bleve/v2 v2.5.2
|
||||
github.com/buildkite/terminal-to-html/v3 v3.16.8
|
||||
github.com/caddyserver/certmagic v0.22.2
|
||||
github.com/chi-middleware/proxy v1.1.1
|
||||
github.com/djherbis/buffer v1.2.0
|
||||
github.com/djherbis/nio/v3 v3.0.1
|
||||
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/editorconfig/editorconfig-core-go/v2 v2.6.3
|
||||
github.com/emersion/go-imap v1.2.1
|
||||
github.com/felixge/fgprof v0.9.5
|
||||
github.com/fsnotify/fsnotify v1.8.0
|
||||
github.com/gliderlabs/ssh v0.3.8
|
||||
github.com/go-ap/activitypub v0.0.0-20231114162308-e219254dc5c9
|
||||
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73
|
||||
github.com/go-chi/chi/v5 v5.2.0
|
||||
github.com/go-chi/cors v1.2.1
|
||||
github.com/go-co-op/gocron v1.37.0
|
||||
github.com/go-enry/go-enry/v2 v2.9.2
|
||||
github.com/go-git/go-git/v5 v5.13.2
|
||||
github.com/go-ldap/ldap/v3 v3.4.6
|
||||
github.com/go-openapi/spec v0.20.14
|
||||
github.com/go-sql-driver/mysql v1.9.1
|
||||
github.com/go-webauthn/webauthn v0.12.2
|
||||
github.com/gobwas/glob v0.2.3
|
||||
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f
|
||||
github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
|
||||
github.com/google/go-github/v64 v64.0.0
|
||||
github.com/google/pprof v0.0.0-20241017200806-017d972448fc
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/feeds v1.2.0
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
github.com/hashicorp/go-version v1.7.0
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7
|
||||
github.com/huandu/xstrings v1.5.0
|
||||
github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056
|
||||
github.com/jhillyerd/enmime/v2 v2.1.0
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
|
||||
github.com/klauspost/compress v1.17.11
|
||||
github.com/klauspost/cpuid/v2 v2.2.10
|
||||
github.com/lib/pq v1.10.9
|
||||
github.com/markbates/goth v1.80.0
|
||||
github.com/mattn/go-isatty v0.0.20
|
||||
github.com/mattn/go-sqlite3 v1.14.28
|
||||
github.com/meilisearch/meilisearch-go v0.31.0
|
||||
github.com/mholt/archiver/v3 v3.5.1
|
||||
github.com/microcosm-cc/bluemonday v1.0.27
|
||||
github.com/minio/minio-go/v7 v7.0.88
|
||||
github.com/msteinert/pam/v2 v2.1.0
|
||||
github.com/nektos/act v0.2.52
|
||||
github.com/niklasfasching/go-org v1.7.0
|
||||
github.com/olivere/elastic/v7 v7.0.32
|
||||
github.com/opencontainers/go-digest v1.0.0
|
||||
github.com/opencontainers/image-spec v1.1.1
|
||||
github.com/pquerna/otp v1.4.0
|
||||
github.com/prometheus/client_golang v1.21.1
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1
|
||||
github.com/sassoftware/go-rpmutils v0.4.0
|
||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3
|
||||
github.com/shurcooL/vfsgen v0.0.0-20230704071429-0000e147ea92
|
||||
github.com/stretchr/testify v1.10.0
|
||||
github.com/syndtr/goleveldb v1.0.0
|
||||
github.com/ulikunitz/xz v0.5.12
|
||||
github.com/urfave/cli/v2 v2.27.6
|
||||
github.com/valyala/fastjson v1.6.4
|
||||
github.com/yohcop/openid-go v1.0.1
|
||||
github.com/yuin/goldmark v1.7.8
|
||||
github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc
|
||||
gitlab.com/gitlab-org/api/client-go v0.126.0
|
||||
go.uber.org/mock v0.5.0
|
||||
golang.org/x/crypto v0.36.0
|
||||
golang.org/x/image v0.25.0
|
||||
golang.org/x/net v0.38.0
|
||||
golang.org/x/oauth2 v0.28.0
|
||||
golang.org/x/sync v0.12.0
|
||||
golang.org/x/sys v0.31.0
|
||||
golang.org/x/text v0.23.0
|
||||
google.golang.org/protobuf v1.36.4
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||
gopkg.in/ini.v1 v1.67.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
mvdan.cc/xurls/v2 v2.5.0
|
||||
xorm.io/builder v0.3.13
|
||||
xorm.io/xorm v1.3.9
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute/metadata v0.6.0 // indirect
|
||||
dario.cat/mergo v1.0.0 // indirect
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect
|
||||
github.com/DataDog/zstd v1.5.5 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/RoaringBitmap/roaring/v2 v2.4.5 // indirect
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.22.0 // indirect
|
||||
github.com/blevesearch/bleve_index_api v1.2.8 // indirect
|
||||
github.com/blevesearch/geo v0.2.3 // indirect
|
||||
github.com/blevesearch/go-faiss v1.0.25 // indirect
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3 // indirect
|
||||
github.com/blevesearch/gtreap v0.1.1 // indirect
|
||||
github.com/blevesearch/mmap-go v1.0.4 // indirect
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.3.10 // indirect
|
||||
github.com/blevesearch/segment v0.9.1 // indirect
|
||||
github.com/blevesearch/snowballstem v0.9.0 // indirect
|
||||
github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect
|
||||
github.com/blevesearch/vellum v1.1.0 // indirect
|
||||
github.com/blevesearch/zapx/v11 v11.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v12 v12.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v13 v13.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v14 v14.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v15 v15.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v16 v16.2.4 // indirect
|
||||
github.com/boombuler/barcode v1.0.1 // indirect
|
||||
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874 // indirect
|
||||
github.com/caddyserver/zerossl v0.1.3 // indirect
|
||||
github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudflare/circl v1.6.1 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
|
||||
github.com/cyphar/filepath-securejoin v0.3.6 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/davidmz/go-pageant v1.0.2 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dlclark/regexp2 v1.11.4 // indirect
|
||||
github.com/emersion/go-sasl v0.0.0-20231106173351-e73c9f7bad43 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/fatih/color v1.16.0 // indirect
|
||||
github.com/fxamacker/cbor/v2 v2.8.0 // indirect
|
||||
github.com/go-ap/errors v0.0.0-20231003111023-183eef4b31b7 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||
github.com/go-enry/go-oniguruma v1.2.1 // indirect
|
||||
github.com/go-fed/httpsig v1.1.0 // indirect
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.20.2 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.4 // indirect
|
||||
github.com/go-openapi/swag v0.22.7 // indirect
|
||||
github.com/go-webauthn/x v0.1.20 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/google/btree v1.1.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/go-tpm v0.9.3 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||
github.com/klauspost/pgzip v1.2.6 // indirect
|
||||
github.com/libdns/libdns v0.2.3 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
github.com/markbates/going v1.0.3 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mholt/acmez/v3 v3.1.1 // indirect
|
||||
github.com/miekg/dns v1.1.63 // indirect
|
||||
github.com/minio/crc64nvme v1.0.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mrjones/oauth v0.0.0-20190623134757-126b35219450 // indirect
|
||||
github.com/mschoch/smat v0.2.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/nwaples/rardecode v1.1.3 // indirect
|
||||
github.com/olekukonko/tablewriter v0.0.5 // indirect
|
||||
github.com/onsi/ginkgo v1.16.5 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.21 // indirect
|
||||
github.com/pjbgf/sha1cd v0.3.2 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.62.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/rhysd/actionlint v1.6.27 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/skeema/knownhosts v1.3.0 // indirect
|
||||
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
|
||||
github.com/zeebo/assert v1.3.0 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
go.etcd.io/bbolt v1.4.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
go.uber.org/zap/exp v0.3.0 // indirect
|
||||
golang.org/x/mod v0.24.0 // indirect
|
||||
golang.org/x/time v0.10.0 // indirect
|
||||
golang.org/x/tools v0.31.0 // indirect
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
)
|
||||
|
||||
replace github.com/hashicorp/go-version => github.com/6543/go-version v1.3.1
|
||||
|
||||
replace github.com/shurcooL/vfsgen => github.com/lunny/vfsgen v0.0.0-20220105142115-2c99e1ffdfa0
|
||||
|
||||
replace github.com/nektos/act => code.forgejo.org/forgejo/act v1.25.1
|
||||
|
||||
replace github.com/mholt/archiver/v3 => code.forgejo.org/forgejo/archiver/v3 v3.5.1
|
||||
|
||||
replace github.com/gliderlabs/ssh => code.forgejo.org/forgejo/ssh v0.0.0-20241211213324-5fc306ca0616
|
||||
|
||||
replace git.sr.ht/~mariusor/go-xsd-duration => code.forgejo.org/forgejo/go-xsd-duration v0.0.0-20220703122237-02e73435a078
|
||||
|
||||
require github.com/netkingdom/access-engine v0.0.0
|
||||
|
||||
replace github.com/netkingdom/access-engine => ./third_party/access-engine-pep
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,115 @@
|
|||
// Copyright 2026 The Forgejo Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package oauth2
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/markbates/goth"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
"github.com/netkingdom/access-engine/pkg/decisionpep"
|
||||
)
|
||||
|
||||
var errApplicationDecision = errors.New("current authenticated application access refused")
|
||||
|
||||
// AccessEngineAdmission contains owner-admitted public trust, with only a file
|
||||
// reference to the private PDP caller token. It is not persisted OAuth source
|
||||
// configuration and cannot be replaced by token claims or provider discovery.
|
||||
type AccessEngineAdmission struct {
|
||||
SourceName string `json:"source_name"`
|
||||
Issuer string `json:"issuer"`
|
||||
Audience string `json:"audience"`
|
||||
TokenType string `json:"token_type"`
|
||||
Algorithms []string `json:"algorithms"`
|
||||
IdentityKeys map[string]string `json:"identity_keys"`
|
||||
TenantClaim string `json:"tenant_claim"`
|
||||
PrincipalTypeClaim string `json:"principal_type_claim"`
|
||||
AssuranceClaim string `json:"assurance_claim"`
|
||||
MaxIdentityAge string `json:"max_identity_age"`
|
||||
Decision decisionpep.Admission `json:"decision"`
|
||||
}
|
||||
|
||||
// VerifiedApplicationIdentity is derived only by VerifyApplicationIdentity from
|
||||
// independently admitted JOSE keys. RawData and UserInfo never supply these
|
||||
// fields. This snapshot is an identity fact, never an authorization verdict.
|
||||
type VerifiedApplicationIdentity struct {
|
||||
Issuer string
|
||||
Subject string
|
||||
Tenant string
|
||||
PrincipalType api.SubjectType
|
||||
Assurance string
|
||||
NotAfter time.Time
|
||||
}
|
||||
|
||||
func loadAccessEngineAdmission(path string)(AccessEngineAdmission,error){
|
||||
var a AccessEngineAdmission
|
||||
if !filepath.IsAbs(path){return a,errApplicationDecision}
|
||||
f,e:=os.Open(path);if e!=nil{return a,errApplicationDecision};defer f.Close()
|
||||
stat,e:=f.Stat();if e!=nil||!stat.Mode().IsRegular()||stat.Mode().Perm()&0022!=0{return a,errApplicationDecision}
|
||||
raw,e:=io.ReadAll(io.LimitReader(f,1<<20+1));if e!=nil||len(raw)>1<<20{return a,errApplicationDecision}
|
||||
d:=json.NewDecoder(strings.NewReader(string(raw)));d.DisallowUnknownFields()
|
||||
if d.Decode(&a)!=nil{return a,errApplicationDecision};if _,e=d.Token();e!=io.EOF{return a,errApplicationDecision}
|
||||
return a,nil
|
||||
}
|
||||
|
||||
// VerifyApplicationIdentity validates the ID token independently of Goth's
|
||||
// decode/claim checks and of the UserInfo merge. Keys and accepted algorithm,
|
||||
// issuer, audience and type are admitted separately; none come from the JWT URL.
|
||||
func VerifyApplicationIdentity(raw string,a AccessEngineAdmission,now time.Time)(VerifiedApplicationIdentity,error){
|
||||
var out VerifiedApplicationIdentity
|
||||
age,e:=time.ParseDuration(a.MaxIdentityAge)
|
||||
if e!=nil||age<=0||a.Issuer==""||a.Audience==""||a.TokenType==""||len(a.Algorithms)==0||len(a.IdentityKeys)==0||a.TenantClaim==""||a.PrincipalTypeClaim==""||a.AssuranceClaim==""{return out,errApplicationDecision}
|
||||
for _,alg:=range a.Algorithms{if alg!="RS256"&&alg!="RS384"&&alg!="RS512"&&alg!="ES256"&&alg!="ES384"&&alg!="ES512"&&alg!="EdDSA"{return out,errApplicationDecision}}
|
||||
claims:=jwt.MapClaims{}
|
||||
token,e:=jwt.ParseWithClaims(raw,claims,func(t *jwt.Token)(any,error){
|
||||
if typ,ok:=t.Header["typ"].(string);!ok||typ!=a.TokenType{return nil,errApplicationDecision}
|
||||
kid,ok:=t.Header["kid"].(string);if !ok||kid==""{return nil,errApplicationDecision}
|
||||
text,ok:=a.IdentityKeys[kid];if !ok{return nil,errApplicationDecision}
|
||||
block,rest:=pem.Decode([]byte(text));if block==nil||block.Type!="PUBLIC KEY"||len(strings.TrimSpace(string(rest)))!=0{return nil,errApplicationDecision}
|
||||
key,e:=x509.ParsePKIXPublicKey(block.Bytes);if e!=nil{return nil,errApplicationDecision}
|
||||
var pub crypto.PublicKey=key;return pub,nil
|
||||
},jwt.WithValidMethods(a.Algorithms),jwt.WithIssuer(a.Issuer),jwt.WithAudience(a.Audience),jwt.WithExpirationRequired(),jwt.WithIssuedAt(),jwt.WithJSONNumber(),jwt.WithTimeFunc(func()time.Time{return now}))
|
||||
if e!=nil||token==nil||!token.Valid{return out,errApplicationDecision}
|
||||
subject,e:=claims.GetSubject();if e!=nil||subject==""{return out,errApplicationDecision}
|
||||
issued,e:=claims.GetIssuedAt();if e!=nil||issued==nil||issued.Time.After(now)||now.Sub(issued.Time)>age{return out,errApplicationDecision}
|
||||
end,e:=claims.GetExpirationTime();if e!=nil||end==nil||!now.Before(end.Time){return out,errApplicationDecision}
|
||||
aud,e:=claims.GetAudience();if e!=nil{return out,errApplicationDecision};if len(aud)>1 {if azp,ok:=claims["azp"].(string);!ok||azp!=a.Audience{return out,errApplicationDecision}}
|
||||
value:=func(name string)(string,bool){v,ok:=claims[name].(string);return v,ok&&validClaimLiteral(v)}
|
||||
tenant,ok:=value(a.TenantClaim);if !ok{return out,errApplicationDecision}
|
||||
principal,ok:=value(a.PrincipalTypeClaim);if !ok{return out,errApplicationDecision}
|
||||
assurance,ok:=value(a.AssuranceClaim);if !ok{return out,errApplicationDecision}
|
||||
return VerifiedApplicationIdentity{Issuer:a.Issuer,Subject:subject,Tenant:tenant,PrincipalType:api.SubjectType(principal),Assurance:assurance,NotAfter:end.Time},nil
|
||||
}
|
||||
|
||||
func(source *Source)authorizeAccessEngine(ctx context.Context,user goth.User)error{
|
||||
// The guarded target extension cannot silently fall back to a local group
|
||||
// decision when admission, keys, facts, PDP or caller authentication is absent.
|
||||
if source.Provider!="openidConnect"||ValidateRequiredClaimValues(source.RequiredClaimName,source.RequiredClaimValue,source.RequiredClaimValues)!=nil{return errApplicationDecision}
|
||||
a,e:=loadAccessEngineAdmission(os.Getenv("FORGEJO_ACCESS_ENGINE_ADMISSION_FILE"));if e!=nil||source.authSource==nil||a.SourceName!=source.authSource.Name||a.Audience!=source.ClientID{return errApplicationDecision}
|
||||
identity,e:=VerifyApplicationIdentity(user.IDToken,a,time.Now().UTC());if e!=nil{return errApplicationDecision}
|
||||
// RequireCurrentUserInfoClaim has refused missing/malformed current groups
|
||||
// before Goth can merge. The validated ID subject must still match that join.
|
||||
sub,ok:=user.RawData["sub"].(string);if !ok||sub!=identity.Subject||user.UserID!=identity.Subject{return errApplicationDecision}
|
||||
groups,ok:=strictClaimValues(user.RawData[source.RequiredClaimName]);if !ok{return errApplicationDecision}
|
||||
client,e:=decisionpep.New(a.Decision);if e!=nil{return errApplicationDecision}
|
||||
request:=api.CheckRequest{Tenant:identity.Tenant,
|
||||
Subject:api.SubjectRef{ID:identity.Subject,Type:identity.PrincipalType,Tenant:identity.Tenant,
|
||||
Attributes:map[string]any{"issuer":identity.Issuer,"assurance":identity.Assurance,"current_userinfo_groups":groups}},
|
||||
Action:"application.access",Resource:api.ResourceRef{ID:"application:forgejo",Type:"application",System:"forgejo",Tenant:identity.Tenant},
|
||||
Context:map[string]any{"identity_issuer":identity.Issuer,"identity_subject":identity.Subject,"identity_tenant":identity.Tenant,"identity_principal_type":string(identity.PrincipalType),"identity_assurance":identity.Assurance,"identity_not_after":identity.NotAfter.UTC().Format(time.RFC3339Nano),"current_userinfo_groups":groups,"required_groups_any_of":source.RequiredClaimValues,"source_name":a.SourceName,"source_id":source.authSource.ID}}
|
||||
if _,e=client.Check(ctx,request);e!=nil{return errApplicationDecision}
|
||||
if !time.Now().UTC().Before(identity.NotAfter){return errApplicationDecision}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package oauth2
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func identityFixture(t *testing.T)(AccessEngineAdmission,ed25519.PrivateKey,jwt.MapClaims,time.Time){
|
||||
t.Helper();pub,key,e:=ed25519.GenerateKey(rand.Reader);if e!=nil{t.Fatal(e)}
|
||||
der,e:=x509.MarshalPKIXPublicKey(pub);if e!=nil{t.Fatal(e)}
|
||||
now:=time.Now().UTC().Truncate(time.Second)
|
||||
a:=AccessEngineAdmission{Issuer:"https://issuer.invalid",Audience:"forgejo",TokenType:"JWT",Algorithms:[]string{"EdDSA"},IdentityKeys:map[string]string{"synthetic":string(pem.EncodeToMemory(&pem.Block{Type:"PUBLIC KEY",Bytes:der}))},TenantClaim:"tenant",PrincipalTypeClaim:"principal_type",AssuranceClaim:"acr",MaxIdentityAge:"5m"}
|
||||
c:=jwt.MapClaims{"iss":a.Issuer,"aud":a.Audience,"sub":"user:synthetic","iat":now.Add(-time.Second).Unix(),"exp":now.Add(time.Minute).Unix(),"tenant":"tenant:synthetic","principal_type":"human","acr":"aal2"}
|
||||
return a,key,c,now
|
||||
}
|
||||
func signedIdentity(t *testing.T,key ed25519.PrivateKey,c jwt.MapClaims,mutate func(*jwt.Token))string{
|
||||
t.Helper();token:=jwt.NewWithClaims(jwt.SigningMethodEdDSA,c);token.Header["kid"]="synthetic";token.Header["typ"]="JWT";if mutate!=nil{mutate(token)}
|
||||
raw,e:=token.SignedString(key);if e!=nil{t.Fatal(e)};return raw
|
||||
}
|
||||
func TestVerifiedApplicationIdentityActualJOSE(t *testing.T){
|
||||
a,key,c,now:=identityFixture(t);raw:=signedIdentity(t,key,c,nil)
|
||||
got,e:=VerifyApplicationIdentity(raw,a,now);if e!=nil{t.Fatal(e)}
|
||||
if got.Subject!="user:synthetic"||got.Tenant!="tenant:synthetic"||got.Assurance!="aal2"||got.Issuer!=a.Issuer||string(got.PrincipalType)!="human"{t.Fatal("identity did not come from verified token")}
|
||||
cases:=map[string]func(jwt.MapClaims){"issuer":func(c jwt.MapClaims){c["iss"]="https://other.invalid"},"audience":func(c jwt.MapClaims){c["aud"]="other"},"expired":func(c jwt.MapClaims){c["exp"]=now.Add(-time.Nanosecond).Unix()},"future-issued":func(c jwt.MapClaims){c["iat"]=now.Add(time.Minute).Unix()},"old-issued":func(c jwt.MapClaims){c["iat"]=now.Add(-10*time.Minute).Unix()},"no-exp":func(c jwt.MapClaims){delete(c,"exp")},"no-iat":func(c jwt.MapClaims){delete(c,"iat")},"no-tenant":func(c jwt.MapClaims){delete(c,"tenant")},"no-principal":func(c jwt.MapClaims){delete(c,"principal_type")},"no-assurance":func(c jwt.MapClaims){delete(c,"acr")},"multi-audience-no-azp":func(c jwt.MapClaims){c["aud"]=[]string{"forgejo","other"}},"empty-subject":func(c jwt.MapClaims){c["sub"]=""}}
|
||||
for name,change:=range cases{t.Run(name,func(t *testing.T){copy:=jwt.MapClaims{};for k,v:=range c{copy[k]=v};change(copy);if _,e:=VerifyApplicationIdentity(signedIdentity(t,key,copy,nil),a,now);e==nil{t.Fatal("unverified identity accepted")}})}
|
||||
t.Run("wrong-key",func(t *testing.T){_,other,_:=ed25519.GenerateKey(rand.Reader);if _,e:=VerifyApplicationIdentity(signedIdentity(t,other,c,nil),a,now);e==nil{t.Fatal("wrong key accepted")}})
|
||||
t.Run("unknown-key",func(t *testing.T){if _,e:=VerifyApplicationIdentity(signedIdentity(t,key,c,func(t *jwt.Token){t.Header["kid"]="other"}),a,now);e==nil{t.Fatal("unknown key accepted")}})
|
||||
t.Run("wrong-type",func(t *testing.T){if _,e:=VerifyApplicationIdentity(signedIdentity(t,key,c,func(t *jwt.Token){t.Header["typ"]="at+jwt"}),a,now);e==nil{t.Fatal("access token accepted as ID token")}})
|
||||
t.Run("algorithm-confusion",func(t *testing.T){token:=jwt.NewWithClaims(jwt.SigningMethodHS256,c);token.Header["kid"]="synthetic";token.Header["typ"]="JWT";raw,_:=token.SignedString([]byte(a.IdentityKeys["synthetic"]));if _,e:=VerifyApplicationIdentity(raw,a,now);e==nil{t.Fatal("algorithm confusion accepted")}})
|
||||
t.Run("none",func(t *testing.T){token:=jwt.NewWithClaims(jwt.SigningMethodNone,c);token.Header["kid"]="synthetic";token.Header["typ"]="JWT";raw,_:=token.SignedString(jwt.UnsafeAllowNoneSignatureType);if _,e:=VerifyApplicationIdentity(raw,a,now);e==nil{t.Fatal("unsigned identity accepted")}})
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
// Copyright 2021 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package oauth2
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/markbates/goth"
|
||||
"github.com/markbates/goth/gothic"
|
||||
)
|
||||
|
||||
// Callout redirects request/response pair to authenticate against the provider
|
||||
func (source *Source) Callout(request *http.Request, response http.ResponseWriter, codeChallengeS256 string) error {
|
||||
// not sure if goth is thread safe (?) when using multiple providers
|
||||
request.Header.Set(ProviderHeaderKey, source.authSource.Name)
|
||||
|
||||
var querySuffix string
|
||||
if codeChallengeS256 != "" {
|
||||
querySuffix = "&" + url.Values{
|
||||
"code_challenge_method": []string{"S256"},
|
||||
"code_challenge": []string{codeChallengeS256},
|
||||
}.Encode()
|
||||
}
|
||||
|
||||
// don't use the default gothic begin handler to prevent issues when some error occurs
|
||||
// normally the gothic library will write some custom stuff to the response instead of our own nice error page
|
||||
// gothic.BeginAuthHandler(response, request)
|
||||
|
||||
gothRWMutex.RLock()
|
||||
defer gothRWMutex.RUnlock()
|
||||
|
||||
url, err := gothic.GetAuthURL(response, request)
|
||||
if err == nil {
|
||||
// hacky way to set the code_challenge, but no better way until
|
||||
// https://github.com/markbates/goth/issues/516 is resolved
|
||||
http.Redirect(response, request, url+querySuffix, http.StatusTemporaryRedirect)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Callback handles OAuth callback, resolve to a goth user and send back to original url
|
||||
// this will trigger a new authentication request, but because we save it in the session we can use that
|
||||
func (source *Source) Callback(request *http.Request, response http.ResponseWriter, codeVerifier string) (goth.User, error) {
|
||||
// not sure if goth is thread safe (?) when using multiple providers
|
||||
request.Header.Set(ProviderHeaderKey, source.authSource.Name)
|
||||
|
||||
if codeVerifier != "" {
|
||||
// hacky way to set the code_verifier...
|
||||
// Will be picked up inside CompleteUserAuth: params := req.URL.Query()
|
||||
// https://github.com/markbates/goth/pull/474/files
|
||||
request = request.Clone(request.Context())
|
||||
q := request.URL.Query()
|
||||
q.Add("code_verifier", codeVerifier)
|
||||
request.URL.RawQuery = q.Encode()
|
||||
}
|
||||
|
||||
gothRWMutex.RLock()
|
||||
defer gothRWMutex.RUnlock()
|
||||
|
||||
user, err := gothic.CompleteUserAuth(response, request)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
if source.RequiredClaimValues != nil {
|
||||
if err := source.authorizeAccessEngine(request.Context(), user); err != nil {
|
||||
return goth.User{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
{
|
||||
"argv": [
|
||||
"/usr/bin/bwrap",
|
||||
"--unshare-net",
|
||||
"--unshare-pid",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--symlink",
|
||||
"usr/bin",
|
||||
"/bin",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--bind",
|
||||
"/tmp/apps-pdp-forgejo-actual-bs7nxdhk",
|
||||
"/work",
|
||||
"--ro-bind",
|
||||
"/tmp/forgejo-independent-r1/go",
|
||||
"/toolchain",
|
||||
"--ro-bind",
|
||||
"/tmp/forgejo-independent-r1/gomodcache",
|
||||
"/modules",
|
||||
"--bind",
|
||||
"/tmp/apps-accessengine-adapter-tests-ulc9rfnf/gocache",
|
||||
"/adapter-cache",
|
||||
"--chdir",
|
||||
"/work/source",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"PATH",
|
||||
"/toolchain/bin:/usr/bin:/bin",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work/home",
|
||||
"--setenv",
|
||||
"GOPROXY",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOSUMDB",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOTOOLCHAIN",
|
||||
"local",
|
||||
"--setenv",
|
||||
"GOCACHE",
|
||||
"/adapter-cache",
|
||||
"--setenv",
|
||||
"GOMODCACHE",
|
||||
"/modules",
|
||||
"--setenv",
|
||||
"GOMAXPROCS",
|
||||
"4",
|
||||
"--setenv",
|
||||
"CGO_ENABLED",
|
||||
"1",
|
||||
"--",
|
||||
"go",
|
||||
"test",
|
||||
"-p",
|
||||
"4",
|
||||
"-json",
|
||||
"-tags",
|
||||
"sqlite sqlite_unlock_notify",
|
||||
"./services/auth/source/oauth2",
|
||||
"-run",
|
||||
"TestVerifiedApplicationIdentityActualJOSE|TestRequired|TestCurrent",
|
||||
"-count=1"
|
||||
],
|
||||
"returncode": 1,
|
||||
"workspace": "/tmp/apps-pdp-forgejo-actual-bs7nxdhk",
|
||||
"seconds": 15.41,
|
||||
"all_owned_processes_terminal": true
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
go: updates to go.mod needed; to update it:
|
||||
go mod tidy
|
||||
|
|
@ -0,0 +1,757 @@
|
|||
// Command flex-auth is the CLI entry point for the flex-auth authorization
|
||||
// registry and control plane.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/audit"
|
||||
"github.com/netkingdom/access-engine/internal/callerauth"
|
||||
decisioncore "github.com/netkingdom/access-engine/internal/decision"
|
||||
"github.com/netkingdom/access-engine/internal/emission"
|
||||
"github.com/netkingdom/access-engine/internal/policy"
|
||||
"github.com/netkingdom/access-engine/internal/registry"
|
||||
"github.com/netkingdom/access-engine/internal/taskexecution"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// version is set at build time via -ldflags "-X main.version=...".
|
||||
var version = "0.0.0-dev"
|
||||
|
||||
func main() {
|
||||
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
|
||||
}
|
||||
|
||||
func run(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
printUsage(stderr)
|
||||
return 64
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "version", "--version", "-version":
|
||||
fmt.Fprintln(stdout, version)
|
||||
return 0
|
||||
case "validate":
|
||||
return runValidate(args[1:], stdout, stderr)
|
||||
case "load-registry":
|
||||
return runLoadRegistry(args[1:], stdout, stderr)
|
||||
case "test-policy":
|
||||
return runTestPolicy(args[1:], stdout, stderr)
|
||||
case "check":
|
||||
return runCheck(args[1:], stdout, stderr)
|
||||
case "batch-check":
|
||||
return runBatchCheck(args[1:], stdout, stderr)
|
||||
case "list-allowed":
|
||||
return runListAllowed(args[1:], stdout, stderr)
|
||||
case "explain":
|
||||
return runExplain(args[1:], stdout, stderr)
|
||||
case "serve":
|
||||
return runServe(args[1:], stdout, stderr)
|
||||
case "serve-readback":
|
||||
return runServeReadback(args[1:], stdout, stderr)
|
||||
case "help", "-h", "--help":
|
||||
printUsage(stdout)
|
||||
return 0
|
||||
default:
|
||||
fmt.Fprintf(stderr, "access-engine: unknown subcommand %q\n", args[0])
|
||||
printUsage(stderr)
|
||||
return 64
|
||||
}
|
||||
}
|
||||
|
||||
func runValidate(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("validate", stderr)
|
||||
kind := fs.String("kind", "", "resource-manifest, subject-manifest, protected-system, relationship, access-descriptor, or policy")
|
||||
file := fs.String("file", "", "YAML/JSON file to validate")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *kind == "" || *file == "" {
|
||||
fmt.Fprintln(stderr, "validate requires --kind and --file")
|
||||
return 64
|
||||
}
|
||||
|
||||
switch *kind {
|
||||
case "resource-manifest":
|
||||
var manifest api.ResourceManifest
|
||||
if err := readYAML(*file, &manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().ImportResourceManifest(manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "subject-manifest":
|
||||
var manifest api.SubjectManifest
|
||||
if err := readYAML(*file, &manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().ImportSubjectManifest(manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "protected-system":
|
||||
var manifest api.ProtectedSystemManifest
|
||||
if err := readYAML(*file, &manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().PutProtectedSystem(manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "relationship":
|
||||
var fact api.RelationshipFact
|
||||
if err := readYAML(*file, &fact); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().PutRelationship(fact); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "access-descriptor":
|
||||
var descriptor api.CaringAccessDescriptor
|
||||
if err := readYAML(*file, &descriptor); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := validateDescriptor(descriptor); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "policy", "policy-package":
|
||||
pkg, err := policy.LoadAndValidateFile(context.Background(), *file)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, pkg.Validation); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if !pkg.Valid {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
default:
|
||||
fmt.Fprintf(stderr, "unsupported validate kind %q\n", *kind)
|
||||
return 64
|
||||
}
|
||||
|
||||
return writeStatus(stdout, "valid", map[string]any{"kind": *kind, "file": *file})
|
||||
}
|
||||
|
||||
func runLoadRegistry(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("load-registry", stderr)
|
||||
file := fs.String("file", "", "registry snapshot JSON file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *file == "" {
|
||||
fmt.Fprintln(stderr, "load-registry requires --file")
|
||||
return 64
|
||||
}
|
||||
|
||||
store, err := registry.LoadFile(*file)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
snapshot := store.Snapshot()
|
||||
return writeStatus(stdout, "loaded", map[string]any{
|
||||
"file": *file,
|
||||
"systems": len(snapshot.Systems),
|
||||
"resource_manifests": len(snapshot.ResourceManifests),
|
||||
"subjects": len(snapshot.Subjects),
|
||||
"groups": len(snapshot.Groups),
|
||||
"teams": len(snapshot.Teams),
|
||||
"tenants": len(snapshot.Tenants),
|
||||
"relationships": len(snapshot.Relationships),
|
||||
})
|
||||
}
|
||||
|
||||
func runTestPolicy(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("test-policy", stderr)
|
||||
file := fs.String("file", "", "policy package Markdown file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *file == "" {
|
||||
fmt.Fprintln(stderr, "test-policy requires --file")
|
||||
return 64
|
||||
}
|
||||
|
||||
pkg, err := policy.LoadAndValidateFile(context.Background(), *file)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, pkg.Validation); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if !pkg.Valid {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runCheck(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("check", stderr)
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
requestPath := fs.String("request", "", "check request YAML/JSON file")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" || *requestPath == "" {
|
||||
fmt.Fprintln(stderr, "check requires --registry, --policy, and --request")
|
||||
return 64
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var request api.CheckRequest
|
||||
if err := readYAML(*requestPath, &request); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
decision, err := engine.Check(context.Background(), request)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, decision); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runBatchCheck(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("batch-check", stderr)
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
requestPath := fs.String("request", "", "batch check request YAML/JSON file")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" || *requestPath == "" {
|
||||
fmt.Fprintln(stderr, "batch-check requires --registry, --policy, and --request")
|
||||
return 64
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var request api.BatchCheckRequest
|
||||
if err := readYAML(*requestPath, &request); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
decisions, err := engine.BatchCheck(context.Background(), request)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, decisions); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runListAllowed(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("list-allowed", stderr)
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
subject := fs.String("subject", "", "subject id")
|
||||
action := fs.String("action", "", "action name")
|
||||
system := fs.String("system", "", "protected system id")
|
||||
resourceType := fs.String("resource-type", "", "resource type")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
var filters keyValueFlags
|
||||
fs.Var(&filters, "filter", "resource filter as key=value; may be repeated")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" || *subject == "" || *action == "" {
|
||||
fmt.Fprintln(stderr, "list-allowed requires --registry, --policy, --subject, and --action")
|
||||
return 64
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
decisions, err := engine.ListAllowed(context.Background(), decisioncore.ListAllowedRequest{
|
||||
Subject: api.SubjectRef{ID: *subject},
|
||||
Action: *action,
|
||||
System: *system,
|
||||
ResourceType: *resourceType,
|
||||
Filters: filters.Map(),
|
||||
})
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, decisions); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runExplain(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("explain", stderr)
|
||||
logPath := fs.String("decision-log", "", "JSONL decision log path")
|
||||
decisionID := fs.String("decision-id", "", "decision id to explain")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *logPath == "" || *decisionID == "" {
|
||||
fmt.Fprintln(stderr, "explain requires --decision-log and --decision-id")
|
||||
return 64
|
||||
}
|
||||
|
||||
log := audit.NewJSONLDecisionLog(*logPath)
|
||||
envelope, ok, err := log.Find(*decisionID)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if !ok {
|
||||
return fail(stderr, fmt.Errorf("decision %q not found", *decisionID))
|
||||
}
|
||||
if err := writeJSON(stdout, decisioncore.ExplainEnvelope(envelope)); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runServe(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("serve", stderr)
|
||||
addr := fs.String("addr", "127.0.0.1:8080", "HTTP listen address")
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
signingKeyFile := fs.String("envelope-signing-key-file", "", "owner-mounted base64url Ed25519 seed file")
|
||||
signingKID := fs.String("envelope-signing-kid", "", "independently admitted envelope signing key id")
|
||||
approvalSourceFile := fs.String("approval-source-file", "", "owner fixed Approval HTTPS reader configuration file")
|
||||
outboxMaxBytes := fs.Int64("outbox-max-bytes", emission.MaxOutboxBytes, "bounded outbox payload bytes, maximum67108864")
|
||||
outboxDir := fs.String("outbox-dir", "", "durable emission outbox directory (FLEX-WP-0031); exclusive with --log")
|
||||
emissionSource := fs.String("emission-source", "", "audit-core source name for emitted decision events, e.g. flex-auth.tenant-engine")
|
||||
auditURL := fs.String("audit-url", "", "admitted audit-core /v1/events endpoint; empty disables drain and heartbeats")
|
||||
auditTokenFile := fs.String("audit-token-file", "", "mounted sender token file, never a token value")
|
||||
callerAuthMode := fs.String("caller-auth-mode", "disabled", "disabled, warn, or enforce")
|
||||
callerAudience := fs.String("caller-audience", "flex-auth", "required caller token audience")
|
||||
callerKubernetesURL := fs.String("caller-kubernetes-url", "https://kubernetes.default.svc", "Kubernetes API base URL for TokenReview")
|
||||
callerReviewerTokenFile := fs.String("caller-reviewer-token-file", "/var/run/secrets/flex-auth-reviewer/token", "projected Kubernetes API credential")
|
||||
callerCAFile := fs.String("caller-ca-file", "/var/run/secrets/flex-auth-reviewer/ca.crt", "Kubernetes API CA bundle")
|
||||
var callerBindings keyValueFlags
|
||||
fs.Var(&callerBindings, "caller-binding", "resource system=authenticated Kubernetes principal (repeatable)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" {
|
||||
fmt.Fprintln(stderr, "serve requires --registry and --policy")
|
||||
return 64
|
||||
}
|
||||
|
||||
if *outboxDir != "" && (*logPath != "" || *emissionSource == "") {
|
||||
fmt.Fprintln(stderr, "serve --outbox-dir requires --emission-source and excludes --log")
|
||||
return 64
|
||||
}
|
||||
delivery := emission.DeliveryConfig{URL: *auditURL, TokenFile: *auditTokenFile}
|
||||
if *auditURL != "" || *auditTokenFile != "" {
|
||||
if *outboxDir == "" {
|
||||
fmt.Fprintln(stderr, "audit delivery requires --outbox-dir")
|
||||
return 64
|
||||
}
|
||||
if err := delivery.Validate(); err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return 64
|
||||
}
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := configureEnvelopeSigning(engine, *signingKeyFile, *signingKID); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var outbox *emission.Outbox
|
||||
if *outboxDir != "" {
|
||||
outbox, err = emission.OpenBounded(*outboxDir, *emissionSource, *outboxMaxBytes)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
defer outbox.Close()
|
||||
engine.SetDecisionLog(outbox)
|
||||
}
|
||||
|
||||
authenticator, err := buildCallerAuthenticator(
|
||||
callerauth.Mode(*callerAuthMode),
|
||||
*callerAudience,
|
||||
*callerKubernetesURL,
|
||||
*callerReviewerTokenFile,
|
||||
*callerCAFile,
|
||||
callerBindings.StringMap(),
|
||||
stderr,
|
||||
)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
|
||||
serviceInputs, err := buildServicePilotInputs(engine, callerauth.Mode(*callerAuthMode), *callerAudience, *callerKubernetesURL, *callerReviewerTokenFile, *callerCAFile, callerBindings.StringMap())
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var approvalReader *taskexecution.ApprovalReader
|
||||
if engine.IsTrustedServicePilot() {
|
||||
if *signingKeyFile == "" || *approvalSourceFile == "" {
|
||||
return fail(stderr, fmt.Errorf("trusted task source requires signing and fixed Approval reader configuration"))
|
||||
}
|
||||
approvalReader, err = taskexecution.LoadApprovalReader(*approvalSourceFile)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
} else if *approvalSourceFile != "" {
|
||||
return fail(stderr, fmt.Errorf("Approval reader requires exact trusted task source package"))
|
||||
}
|
||||
mux := newServeMuxWithTaskFacts(engine, authenticator, serviceInputs, approvalReader)
|
||||
if outbox != nil {
|
||||
mountEmission(mux, outbox)
|
||||
}
|
||||
if *auditURL != "" {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
runEmissionDelivery(ctx, outbox, delivery, stderr)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
}
|
||||
|
||||
fmt.Fprintf(stderr, "access-engine serving on http://%s\n", *addr)
|
||||
if err := http.ListenAndServe(*addr, mux); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runEmissionDelivery(ctx context.Context, outbox *emission.Outbox, config emission.DeliveryConfig, stderr io.Writer) {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := outbox.AppendDueHeartbeats(); err != nil {
|
||||
fmt.Fprintf(stderr, "emission heartbeat commit: %v\n", err)
|
||||
}
|
||||
n, err := outbox.Drain(ctx, config, 100)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
fmt.Fprintf(stderr, "emission drain: %v\n", err)
|
||||
}
|
||||
if err == nil && n == 100 {
|
||||
continue // Drain the next bounded batch without imposing a rate cap.
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newServeMux(engine *decisioncore.Engine) *http.ServeMux {
|
||||
return newServeMuxWithCallerAuth(engine, callerauth.Disabled())
|
||||
}
|
||||
|
||||
func newServeMuxWithCallerAuth(engine *decisioncore.Engine, authenticator *callerauth.Authenticator) *http.ServeMux {
|
||||
return newServeMuxWithServicePilotInputs(engine, authenticator, nil)
|
||||
}
|
||||
|
||||
func newServeMuxWithServicePilotInputs(engine *decisioncore.Engine, authenticator *callerauth.Authenticator, serviceInputs *taskexecution.ServicePilotInputs) *http.ServeMux {
|
||||
return newServeMuxWithTaskFacts(engine, authenticator, serviceInputs, nil)
|
||||
}
|
||||
func newServeMuxWithTaskFacts(engine *decisioncore.Engine, authenticator *callerauth.Authenticator, serviceInputs *taskexecution.ServicePilotInputs, approvalReader *taskexecution.ApprovalReader) *http.ServeMux {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
})
|
||||
mux.HandleFunc("/v1/check", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if engine.IsTaskPin() {
|
||||
if serviceInputs == nil {
|
||||
http.Error(w, "service input unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
decode := taskexecution.DecodeServiceRequest
|
||||
if engine.IsTrustedServicePilot() {
|
||||
decode = taskexecution.DecodeTrustedServiceRequest
|
||||
}
|
||||
request, err := decode(r.Body)
|
||||
if err != nil || request.Purpose != "" {
|
||||
http.Error(w, "invalid service task request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
input, err := serviceInputs.Prepare(r.Context(), r.Header.Get("Authorization"), request, time.Now().UTC())
|
||||
if err != nil {
|
||||
http.Error(w, "service task input refused", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
var decision api.DecisionEnvelope
|
||||
if engine.IsTrustedServicePilot() {
|
||||
decision, err = engine.CheckTrustedService(r.Context(), input, approvalReader)
|
||||
} else {
|
||||
decision, err = engine.CheckServicePilot(r.Context(), input)
|
||||
}
|
||||
writeHTTP(w, decision, err)
|
||||
return
|
||||
}
|
||||
var request api.CheckRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if request.Purpose != "" {
|
||||
// Only the readback pin issues purpose-bearing decisions
|
||||
// (FLEX-DEC-2026-019); an enforcement pin never does.
|
||||
http.Error(w, "purpose is not accepted on /v1/check", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
identity, err := authenticator.Authorize(r.Context(), r.Header.Get("Authorization"), []string{request.Resource.System})
|
||||
if err != nil {
|
||||
writeCallerAuthError(w, err)
|
||||
return
|
||||
}
|
||||
decision, err := engine.Check(callerauth.WithRecord(r.Context(), authenticator.Record(identity)), request)
|
||||
writeHTTP(w, decision, err)
|
||||
})
|
||||
mux.HandleFunc("/v1/batch_check", func(w http.ResponseWriter, r *http.Request) {
|
||||
if engine.IsTaskPin() {
|
||||
http.Error(w, "service task batch unavailable", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var request api.BatchCheckRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
systems := make([]string, 0, len(request.Resources))
|
||||
for _, resource := range request.Resources {
|
||||
systems = append(systems, resource.System)
|
||||
}
|
||||
identity, err := authenticator.Authorize(r.Context(), r.Header.Get("Authorization"), systems)
|
||||
if err != nil {
|
||||
writeCallerAuthError(w, err)
|
||||
return
|
||||
}
|
||||
decisions, err := engine.BatchCheck(callerauth.WithRecord(r.Context(), authenticator.Record(identity)), request)
|
||||
writeHTTP(w, decisions, err)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
// Only the existing exact service pilot package selects this source path.
|
||||
// This is not an eligibility toggle; successful preparation still only DENYs.
|
||||
func buildServicePilotInputs(engine *decisioncore.Engine, mode callerauth.Mode, audience, kubernetesURL, reviewerTokenFile, caFile string, bindings map[string]string) (*taskexecution.ServicePilotInputs, error) {
|
||||
if !engine.IsTaskPin() {
|
||||
return nil, nil
|
||||
}
|
||||
if mode != callerauth.ModeEnforce || audience != "flex-auth" || len(bindings) != 1 || bindings["secrets-engine"] != taskexecution.ServicePilotPrincipal {
|
||||
return nil, fmt.Errorf("service pilot requires exact enforced retained caller mapping")
|
||||
}
|
||||
reviewer, err := callerauth.NewKubernetesTokenReviewer(kubernetesURL, audience, reviewerTokenFile, caFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if engine.IsTrustedServicePilot() {
|
||||
return taskexecution.NewTrustedServiceInputs(reviewer)
|
||||
}
|
||||
return taskexecution.NewServicePilotInputs(reviewer)
|
||||
}
|
||||
|
||||
func buildCallerAuthenticator(mode callerauth.Mode, audience, kubernetesURL, reviewerTokenFile, caFile string, bindings map[string]string, stderr io.Writer) (*callerauth.Authenticator, error) {
|
||||
if mode == callerauth.ModeDisabled {
|
||||
return callerauth.New(mode, nil, "", nil, nil)
|
||||
}
|
||||
reviewer, err := callerauth.NewKubernetesTokenReviewer(kubernetesURL, audience, reviewerTokenFile, caFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return callerauth.New(mode, reviewer, audience, bindings, func(format string, args ...any) {
|
||||
fmt.Fprintf(stderr, format+"\n", args...)
|
||||
})
|
||||
}
|
||||
|
||||
func writeCallerAuthError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, callerauth.ErrUnauthenticated):
|
||||
http.Error(w, "unauthenticated", http.StatusUnauthorized)
|
||||
case errors.Is(err, callerauth.ErrForbidden):
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
default:
|
||||
http.Error(w, "caller authentication unavailable", http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func buildEngine(ctx context.Context, registryPath, policyPath, logPath string) (*decisioncore.Engine, error) {
|
||||
pkg, err := policy.LoadAndValidateFile(ctx, policyPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load := registry.LoadFile
|
||||
if pkg.Metadata.ID == taskexecution.ServicePilotPackageID && pkg.Metadata.Version == taskexecution.TrustedServicePilotPackageVersion {
|
||||
load = registry.LoadFilePreservingNumbers
|
||||
}
|
||||
store, err := load(registryPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
engine, err := decisioncore.NewEngine(store, pkg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if logPath != "" {
|
||||
engine.SetDecisionLog(audit.NewJSONLDecisionLog(logPath))
|
||||
}
|
||||
return engine, nil
|
||||
}
|
||||
|
||||
func validateDescriptor(descriptor api.CaringAccessDescriptor) error {
|
||||
if descriptor.Profile != api.CaringProfileCaring040RC2 {
|
||||
return fmt.Errorf("unsupported CARING profile %q", descriptor.Profile)
|
||||
}
|
||||
if descriptor.SubjectType == "" {
|
||||
return fmt.Errorf("subject_type is required")
|
||||
}
|
||||
if descriptor.OrganizationRelation == "" {
|
||||
return fmt.Errorf("organization_relation is required")
|
||||
}
|
||||
if descriptor.CanonicalRole == "" {
|
||||
return fmt.Errorf("canonical_role is required")
|
||||
}
|
||||
if descriptor.Scope.Level == "" || descriptor.Scope.ID == "" {
|
||||
return fmt.Errorf("scope.level and scope.id are required")
|
||||
}
|
||||
if len(descriptor.Planes) == 0 {
|
||||
return fmt.Errorf("at least one plane is required")
|
||||
}
|
||||
if len(descriptor.Capabilities) == 0 {
|
||||
return fmt.Errorf("at least one capability is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readYAML(path string, out any) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := yaml.Unmarshal(data, out); err != nil {
|
||||
return fmt.Errorf("unmarshal %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w io.Writer, value any) error {
|
||||
encoder := json.NewEncoder(w)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(value); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeStatus(w io.Writer, status string, extra map[string]any) int {
|
||||
out := map[string]any{"status": status}
|
||||
for key, value := range extra {
|
||||
out[key] = value
|
||||
}
|
||||
if err := writeJSON(w, out); err != nil {
|
||||
return fail(w, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// mountEmission exposes the local half of reconciliation: committed and
|
||||
// released-uncommitted counts per class. Counts only, never records.
|
||||
func mountEmission(mux *http.ServeMux, outbox *emission.Outbox) {
|
||||
mux.HandleFunc("/v1/emission", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
writeHTTP(w, outbox.Status(), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func writeHTTP(w http.ResponseWriter, value any, err error) {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
if errors.Is(err, decisioncore.ErrRecordNotCommitted) || errors.Is(err, decisioncore.ErrServicePilotUnavailable) {
|
||||
// Unavailable evaluation is not an authorization verdict (GH-DEC-2026-024).
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func newFlagSet(name string, stderr io.Writer) *flag.FlagSet {
|
||||
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
return fs
|
||||
}
|
||||
|
||||
func fail(stderr io.Writer, err error) int {
|
||||
fmt.Fprintln(stderr, "access-engine:", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
func printUsage(w io.Writer) {
|
||||
fmt.Fprintln(w, "usage: access-engine <command> [options]")
|
||||
fmt.Fprintln(w, "commands: version, validate, load-registry, test-policy, check, batch-check, list-allowed, explain, serve, serve-readback")
|
||||
}
|
||||
|
||||
type keyValueFlags []string
|
||||
|
||||
func (f *keyValueFlags) String() string {
|
||||
return strings.Join(*f, ",")
|
||||
}
|
||||
|
||||
func (f *keyValueFlags) Set(value string) error {
|
||||
if !strings.Contains(value, "=") {
|
||||
return fmt.Errorf("filter must be key=value")
|
||||
}
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f keyValueFlags) Map() map[string]any {
|
||||
out := make(map[string]any, len(f))
|
||||
for _, item := range f {
|
||||
key, value, _ := strings.Cut(item, "=")
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (f keyValueFlags) StringMap() map[string]string {
|
||||
out := make(map[string]string, len(f))
|
||||
for _, item := range f {
|
||||
key, value, _ := strings.Cut(item, "=")
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
@ -0,0 +1,729 @@
|
|||
package decision
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/callerauth"
|
||||
"github.com/netkingdom/access-engine/internal/policy"
|
||||
"github.com/netkingdom/access-engine/internal/registry"
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/internal/taskexecution"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// Engine evaluates deterministic standalone authorization checks against a
|
||||
// local registry and one validated policy package.
|
||||
type Engine struct {
|
||||
store *registry.Store
|
||||
policy *policy.Package
|
||||
mu sync.RWMutex
|
||||
history map[string]api.DecisionEnvelope
|
||||
log DecisionRecorder
|
||||
clock func() time.Time
|
||||
signingKey ed25519.PrivateKey
|
||||
signingKID string
|
||||
}
|
||||
|
||||
// DecisionRecorder persists decision envelopes.
|
||||
type DecisionRecorder interface {
|
||||
Append(api.DecisionEnvelope) error
|
||||
}
|
||||
|
||||
// BatchRecorder commits several decisions in one durable write.
|
||||
type BatchRecorder interface {
|
||||
AppendBatch([]api.DecisionEnvelope) error
|
||||
}
|
||||
|
||||
// ErrRecordNotCommitted means a decision was withheld because its required
|
||||
// record did not commit (GH-DEC-2026-024). The service answers 503; this is
|
||||
// unavailability, never a substitute authorization verdict.
|
||||
var ErrRecordNotCommitted = errors.New("decision withheld: record not committed")
|
||||
|
||||
// ListAllowedRequest describes a deterministic list_allowed call.
|
||||
type ListAllowedRequest struct {
|
||||
Subject api.SubjectRef `json:"subject"`
|
||||
Action string `json:"action"`
|
||||
System string `json:"system,omitempty"`
|
||||
ResourceType string `json:"resource_type,omitempty"`
|
||||
Filters map[string]any `json:"filters,omitempty"`
|
||||
Context map[string]any `json:"context,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty"`
|
||||
}
|
||||
|
||||
// Explanation is a compact explanation view over a recorded decision.
|
||||
type Explanation struct {
|
||||
DecisionID string `json:"decision_id"`
|
||||
Effect api.DecisionEffect `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Summary string `json:"summary"`
|
||||
Subject api.SubjectRef `json:"subject"`
|
||||
Resource api.ResourceRef `json:"resource"`
|
||||
PolicyPackage string `json:"policy_package,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty"`
|
||||
MatchedRule string `json:"matched_rule,omitempty"`
|
||||
Diagnostics map[string]any `json:"diagnostics,omitempty"`
|
||||
Caring *api.CaringDecisionMetadata `json:"caring,omitempty"`
|
||||
}
|
||||
|
||||
// NewEngine creates a standalone decision engine.
|
||||
func NewEngine(store *registry.Store, policyPackage *policy.Package) (*Engine, error) {
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("registry store is required")
|
||||
}
|
||||
if policyPackage == nil {
|
||||
return nil, fmt.Errorf("policy package is required")
|
||||
}
|
||||
if !policyPackage.Valid {
|
||||
return nil, fmt.Errorf("policy package %q is not valid", policyPackage.Metadata.ID)
|
||||
}
|
||||
return &Engine{
|
||||
store: store,
|
||||
policy: policyPackage,
|
||||
history: make(map[string]api.DecisionEnvelope),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetEnvelopeSigningKey installs an owner-custodied key before serving requests.
|
||||
// The key is copied so caller mutation cannot change the admitted signer.
|
||||
func (e *Engine) SetEnvelopeSigningKey(key ed25519.PrivateKey, kid string) error {
|
||||
if len(key) != ed25519.PrivateKeySize || strings.TrimSpace(kid) == "" {
|
||||
return fmt.Errorf("valid Ed25519 private key and kid are required")
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.signingKey = append(ed25519.PrivateKey(nil), key...)
|
||||
e.signingKID = kid
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDecisionLog attaches a local decision recorder to the engine.
|
||||
func (e *Engine) SetDecisionLog(log DecisionRecorder) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.log = log
|
||||
}
|
||||
|
||||
// SetClock overrides the engine clock. Tests use this to pin allow lifetimes.
|
||||
func (e *Engine) SetClock(clock func() time.Time) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.clock = clock
|
||||
}
|
||||
|
||||
func (e *Engine) now() time.Time {
|
||||
e.mu.RLock()
|
||||
clock := e.clock
|
||||
e.mu.RUnlock()
|
||||
if clock != nil {
|
||||
return clock().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
// decide evaluates one request without recording it.
|
||||
func (e *Engine) decide(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
normalized, facts := e.normalizeRequest(request)
|
||||
|
||||
expectation, err := e.policy.Evaluate(ctx, normalized)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
|
||||
envelope := e.envelope(ctx, normalized, request, expectation, facts)
|
||||
e.mu.RLock()
|
||||
key, kid := e.signingKey, e.signingKID
|
||||
e.mu.RUnlock()
|
||||
if len(key) != 0 {
|
||||
if err := sign.Sign(&envelope, key, kid); err != nil {
|
||||
return api.DecisionEnvelope{}, fmt.Errorf("decision signing failed: %w", err)
|
||||
}
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// IsServicePilot selects the existing exact source package, never a request flag.
|
||||
func (e *Engine) IsServicePilot() bool {
|
||||
return e.policy.Metadata.ID == taskexecution.ServicePilotPackageID && e.policy.Metadata.Version == taskexecution.ServicePilotPackageVersion
|
||||
}
|
||||
func (e *Engine) IsTrustedServicePilot() bool {
|
||||
return e.policy.Metadata.ID == taskexecution.ServicePilotPackageID && e.policy.Metadata.Version == taskexecution.TrustedServicePilotPackageVersion
|
||||
}
|
||||
func (e *Engine) IsTaskPin() bool { return e.IsServicePilot() || e.IsTrustedServicePilot() }
|
||||
|
||||
// ErrServicePilotUnavailable withholds any result that is not this B1 slice's
|
||||
// signed DENY. Provider joins and executable eligibility remain unimplemented.
|
||||
var ErrServicePilotUnavailable = errors.New("service pilot source path unavailable")
|
||||
|
||||
// CheckServicePilot records only a signed DENY after authenticating the exact
|
||||
// immutable service input. It does not validate Approval facts or grant an act.
|
||||
func (e *Engine) CheckServicePilot(ctx context.Context, input taskexecution.ServiceInput) (api.DecisionEnvelope, error) {
|
||||
if !e.IsServicePilot() {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
request, err := input.RequestAt(e.now())
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
envelope, err := e.decide(callerauth.WithRecord(ctx, input.Caller()), request)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
if envelope.Effect != api.DecisionEffectDeny || envelope.Signature == nil || envelope.Signature.Mode != api.EnvelopeSignatureSigned {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
if err := e.recordDecisions([]api.DecisionEnvelope{envelope}); err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// Check evaluates one subject/action/resource request. The decision is
|
||||
// released only after its required record commits (GH-DEC-2026-024).
|
||||
func (e *Engine) Check(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
decision, err := e.decide(ctx, request)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
if err := e.recordDecisions([]api.DecisionEnvelope{decision}); err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// BatchCheck evaluates one subject/action/context tuple against resources in
|
||||
// request order, and commits the whole batch in one durable write.
|
||||
func (e *Engine) BatchCheck(ctx context.Context, request api.BatchCheckRequest) ([]api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return nil, ErrServicePilotUnavailable
|
||||
}
|
||||
decisions := make([]api.DecisionEnvelope, 0, len(request.Resources))
|
||||
for _, resource := range request.Resources {
|
||||
decision, err := e.decide(ctx, api.CheckRequest{
|
||||
ID: request.ID,
|
||||
Tenant: request.Tenant,
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: resource,
|
||||
Context: request.Context,
|
||||
PolicyVersion: request.PolicyVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := e.recordDecisions(decisions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decisions, nil
|
||||
}
|
||||
|
||||
// ListAllowed evaluates candidate resources and returns only allow decisions.
|
||||
func (e *Engine) ListAllowed(ctx context.Context, request ListAllowedRequest) ([]api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return nil, ErrServicePilotUnavailable
|
||||
}
|
||||
candidates := e.store.ResourceRefs(request.System, request.ResourceType)
|
||||
decisions := make([]api.DecisionEnvelope, 0, len(candidates))
|
||||
for _, resource := range candidates {
|
||||
if !resourceMatchesFilters(resource, request.Filters) {
|
||||
continue
|
||||
}
|
||||
decision, err := e.decide(ctx, api.CheckRequest{
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: resource,
|
||||
Context: request.Context,
|
||||
PolicyVersion: request.PolicyVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := e.recordDecisions(decisions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allowed := make([]api.DecisionEnvelope, 0, len(decisions))
|
||||
for _, decision := range decisions {
|
||||
if decision.Effect == api.DecisionEffectAllow {
|
||||
allowed = append(allowed, decision)
|
||||
}
|
||||
}
|
||||
return allowed, nil
|
||||
}
|
||||
|
||||
// Explain returns a CARING-aware explanation for a decision recorded by this
|
||||
// engine instance. P2.6 replaces this in-memory history with the local log.
|
||||
func (e *Engine) Explain(decisionID string) (Explanation, error) {
|
||||
e.mu.RLock()
|
||||
decision, ok := e.history[decisionID]
|
||||
e.mu.RUnlock()
|
||||
if !ok {
|
||||
return Explanation{}, fmt.Errorf("decision %q not found", decisionID)
|
||||
}
|
||||
|
||||
return ExplainEnvelope(decision), nil
|
||||
}
|
||||
|
||||
// ExplainEnvelope returns the same explanation shape for an already-loaded
|
||||
// decision envelope.
|
||||
func ExplainEnvelope(decision api.DecisionEnvelope) Explanation {
|
||||
return Explanation{
|
||||
DecisionID: decision.ID,
|
||||
Effect: decision.Effect,
|
||||
Reason: decision.Reason,
|
||||
Summary: explanationSummary(decision),
|
||||
Subject: decision.Subject,
|
||||
Resource: decision.Resource,
|
||||
PolicyPackage: decision.Provenance.PolicyPackage,
|
||||
PolicyVersion: decision.Provenance.PolicyVersion,
|
||||
MatchedRule: decision.MatchedRule,
|
||||
Diagnostics: decision.Diagnostics,
|
||||
Caring: decision.Caring,
|
||||
}
|
||||
}
|
||||
|
||||
type registryFacts struct {
|
||||
subjectFound bool
|
||||
resourceFound bool
|
||||
subject api.Subject
|
||||
resource api.Resource
|
||||
matchedRelationship string
|
||||
descriptor *api.CaringAccessDescriptor
|
||||
// overriddenByRegistry names request attribute keys whose caller-supplied
|
||||
// value was displaced by a registry fact. Empty on an honest request; a
|
||||
// non-empty list means the caller asserted something the registry contradicts,
|
||||
// which is worth seeing even though the registry won (FLEX-DEC-2026-012).
|
||||
overriddenByRegistry []string
|
||||
}
|
||||
|
||||
func (e *Engine) normalizeRequest(request api.CheckRequest) (api.CheckRequest, registryFacts) {
|
||||
normalized := request
|
||||
facts := registryFacts{}
|
||||
|
||||
overridden := []string{}
|
||||
|
||||
if normalized.Tenant != "" {
|
||||
if normalized.Subject.Tenant == "" {
|
||||
normalized.Subject.Tenant = normalized.Tenant
|
||||
}
|
||||
if normalized.Resource.Tenant == "" {
|
||||
normalized.Resource.Tenant = normalized.Tenant
|
||||
}
|
||||
}
|
||||
|
||||
if subject, ok := e.store.Subject(request.Subject.ID); ok {
|
||||
facts.subjectFound = true
|
||||
facts.subject = subject
|
||||
normalized.Subject = enrichSubjectRef(request.Subject, subject, &overridden)
|
||||
}
|
||||
|
||||
if resource, ok := e.store.Resource(request.Resource.System, request.Resource.ID); ok {
|
||||
facts.resourceFound = true
|
||||
facts.resource = resource
|
||||
normalized.Resource = enrichResourceRef(request.Resource, resource, &overridden)
|
||||
}
|
||||
|
||||
if normalized.CaringContext != nil {
|
||||
descriptor := *normalized.CaringContext
|
||||
facts.descriptor = &descriptor
|
||||
facts.overriddenByRegistry = overridden
|
||||
return normalized, facts
|
||||
}
|
||||
|
||||
facts.overriddenByRegistry = overridden
|
||||
|
||||
if descriptor, relationshipID := e.matchCaringDescriptor(normalized, facts); descriptor != nil {
|
||||
facts.descriptor = descriptor
|
||||
facts.matchedRelationship = relationshipID
|
||||
normalized.CaringContext = descriptor
|
||||
} else if facts.resourceFound && facts.resource.Caring != nil {
|
||||
descriptor := *facts.resource.Caring
|
||||
facts.descriptor = &descriptor
|
||||
normalized.CaringContext = &descriptor
|
||||
}
|
||||
|
||||
return normalized, facts
|
||||
}
|
||||
|
||||
func (e *Engine) matchCaringDescriptor(request api.CheckRequest, facts registryFacts) (*api.CaringAccessDescriptor, string) {
|
||||
candidates := []string{request.Subject.ID}
|
||||
if facts.subjectFound {
|
||||
candidates = append(candidates, facts.subject.Groups...)
|
||||
}
|
||||
|
||||
for _, relationship := range e.store.RelationshipsForObject(request.Resource.ID) {
|
||||
if relationship.Caring == nil {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(candidates, relationship.Subject) {
|
||||
continue
|
||||
}
|
||||
if relationship.System != "" && relationship.System != request.Resource.System {
|
||||
continue
|
||||
}
|
||||
if relationship.Tenant != "" && request.Resource.Tenant != "" && relationship.Tenant != request.Resource.Tenant {
|
||||
continue
|
||||
}
|
||||
descriptor := *relationship.Caring
|
||||
return &descriptor, relationship.ID
|
||||
}
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
// enrichSubjectRef overlays registry facts onto the subject the caller sent.
|
||||
//
|
||||
// Registry facts WIN. A value in the registry is an authority statement; the
|
||||
// same key on the request is the caller's proposal about itself. Letting the
|
||||
// proposal survive made a registry ceiling advisory — see FLEX-DEC-2026-012,
|
||||
// where a caller supplying resource.attributes.allowed_subjects authorized a
|
||||
// subject the registry did not know.
|
||||
//
|
||||
// Keys the registry does not define still pass through from the request. That
|
||||
// residual is stated in docs/request-enrichment.md rather than fixed here: a
|
||||
// policy reading a key its manifest omits is consuming caller input, and the
|
||||
// structural fix is separating the two namespaces (FLEX-WP-0025).
|
||||
func enrichSubjectRef(ref api.SubjectRef, subject api.Subject, overridden *[]string) api.SubjectRef {
|
||||
out := ref
|
||||
// subject.Type is deliberately NOT overwritten, unlike every other registry
|
||||
// fact here. The registry's Type is CARING vocabulary (Human, Agent,
|
||||
// Automation, Service); the request's is the protected system's actor
|
||||
// vocabulary (service, adm, agt, atm). They are two different fields sharing
|
||||
// a name, and substituting one for the other is translation rather than
|
||||
// identity — the error GH-DEC-2026-008 ruled against. Making the registry win
|
||||
// here denied every secrets-engine allow, because "Service" is not "service".
|
||||
//
|
||||
// The residual is that a caller can still assert its own subject.type and
|
||||
// packages branch on it. That is not fixable by overwriting from a different
|
||||
// vocabulary; it needs the two fields separated. FLEX-WP-0025.
|
||||
if out.Type == "" {
|
||||
out.Type = subject.Type
|
||||
}
|
||||
if subject.Tenant != "" {
|
||||
out.Tenant = subject.Tenant
|
||||
}
|
||||
out.Attributes = copyMap(out.Attributes)
|
||||
setAuthoritative(out.Attributes, "display_name", subject.DisplayName, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "organization_relation", subject.OrganizationRelation, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "roles", subject.Roles, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "groups", subject.Groups, "subject", overridden)
|
||||
setAuthoritatives(out.Attributes, subject.Claims, "subject", overridden)
|
||||
setAuthoritatives(out.Attributes, subject.Metadata, "subject", overridden)
|
||||
return out
|
||||
}
|
||||
|
||||
// enrichResourceRef overlays registry facts onto the resource the caller sent.
|
||||
// Registry facts win, for the reason given on enrichSubjectRef: ops-warden's
|
||||
// max_ttl_hours, allowed_subjects, and allowed_principals are ceilings and
|
||||
// allowlists, and a ceiling a caller can raise is not a ceiling.
|
||||
func enrichResourceRef(ref api.ResourceRef, resource api.Resource, overridden *[]string) api.ResourceRef {
|
||||
out := ref
|
||||
if resource.Type != "" {
|
||||
out.Type = resource.Type
|
||||
}
|
||||
out.Attributes = copyMap(out.Attributes)
|
||||
setAuthoritative(out.Attributes, "path", resource.Path, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "parent", resource.Parent, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "labels", resource.Labels, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "trust_zone", resource.TrustZone, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "owner", resource.Owner, "resource", overridden)
|
||||
setAuthoritatives(out.Attributes, resource.Attributes, "resource", overridden)
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *Engine) envelope(ctx context.Context, request, submitted api.CheckRequest, expectation api.DecisionExpectation, facts registryFacts) api.DecisionEnvelope {
|
||||
envelope := api.DecisionEnvelope{
|
||||
RequestID: request.ID,
|
||||
Effect: expectation.Effect,
|
||||
Reason: expectation.Reason,
|
||||
MatchedPolicyVersion: e.policy.Metadata.Version,
|
||||
MatchedRule: expectation.Reason,
|
||||
Resource: request.Resource,
|
||||
Subject: request.Subject,
|
||||
Binding: api.NewDecisionBindingFor(request, submitted),
|
||||
Obligations: expectation.Obligations,
|
||||
Diagnostics: map[string]any{
|
||||
"action": request.Action,
|
||||
"policy_package": e.policy.Metadata.ID,
|
||||
"policy_status": e.policy.Metadata.Status,
|
||||
"registry_subject": facts.subjectFound,
|
||||
"registry_resource": facts.resourceFound,
|
||||
"matched_relationship": facts.matchedRelationship,
|
||||
"registry_overrode": facts.overriddenByRegistry,
|
||||
},
|
||||
Provenance: api.DecisionProvenance{
|
||||
Evaluator: "flex-auth/local",
|
||||
Mode: "standalone",
|
||||
PolicyPackage: e.policy.Metadata.ID,
|
||||
PolicyVersion: e.policy.Metadata.Version,
|
||||
PolicyPackageDigest: e.policy.Digest(),
|
||||
RegistrySnapshotDigest: e.store.Digest(),
|
||||
Caller: callerProvenance(ctx),
|
||||
},
|
||||
Caring: e.caringDecisionMetadata(facts.descriptor, expectation.ConformanceFindings),
|
||||
}
|
||||
api.CompleteDecision(&envelope, request, api.DecisionCompletion{
|
||||
AllowTTL: e.policy.Metadata.AllowTTL,
|
||||
Now: e.now(),
|
||||
})
|
||||
envelope.ID = decisionID(e.policy.Metadata, request, envelope)
|
||||
if envelope.Signature == nil {
|
||||
envelope.Signature = api.UnsignedEnvelopeSignature()
|
||||
}
|
||||
return envelope
|
||||
}
|
||||
|
||||
func callerProvenance(ctx context.Context) *api.CallerProvenance {
|
||||
record, ok := callerauth.RecordFromContext(ctx)
|
||||
if !ok {
|
||||
record = callerauth.Record{Mode: callerauth.ModeDisabled}
|
||||
}
|
||||
out := &api.CallerProvenance{Mode: string(record.Mode)}
|
||||
if record.Principal != "" {
|
||||
out.Principal = record.Principal
|
||||
out.Audience = record.Audience
|
||||
if !record.NotAfter.IsZero() {
|
||||
out.NotAfter = record.NotAfter.UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// recordDecisions releases no effect until its required record commits.
|
||||
// GH-DEC-2026-024 refuses the former restrictive-effect failure exception.
|
||||
// Failed decisions must not enter Explain's history as if they were released.
|
||||
func (e *Engine) recordDecisions(decisions []api.DecisionEnvelope) error {
|
||||
e.mu.RLock()
|
||||
log := e.log
|
||||
e.mu.RUnlock()
|
||||
if log != nil && len(decisions) != 0 {
|
||||
if err := appendAll(log, decisions); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrRecordNotCommitted, err)
|
||||
}
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, decision := range decisions {
|
||||
e.history[decision.ID] = decision
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func appendAll(log DecisionRecorder, decisions []api.DecisionEnvelope) error {
|
||||
if batch, ok := log.(BatchRecorder); ok {
|
||||
return batch.AppendBatch(decisions)
|
||||
}
|
||||
for _, decision := range decisions {
|
||||
if err := log.Append(decision); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) caringDecisionMetadata(descriptor *api.CaringAccessDescriptor, findings []api.CaringConformanceFinding) *api.CaringDecisionMetadata {
|
||||
profile := e.policy.Metadata.Caring.Profile
|
||||
if descriptor != nil && descriptor.Profile != "" {
|
||||
profile = descriptor.Profile
|
||||
}
|
||||
|
||||
metadata := &api.CaringDecisionMetadata{
|
||||
Profile: profile,
|
||||
ConformanceFindings: append([]api.CaringConformanceFinding(nil), findings...),
|
||||
}
|
||||
if descriptor == nil {
|
||||
metadata.ConformanceFindings = append(metadata.ConformanceFindings, api.CaringConformanceFinding{
|
||||
Code: "CARING-DESCRIPTOR-MISSING",
|
||||
Severity: "warning",
|
||||
Message: "no CARING descriptor matched the request",
|
||||
Fields: []string{"caring_context"},
|
||||
})
|
||||
return metadata
|
||||
}
|
||||
|
||||
descriptorCopy := *descriptor
|
||||
metadata.Descriptor = &descriptorCopy
|
||||
metadata.RestrictionsEvaluated = append([]api.Restriction(nil), descriptor.Restrictions...)
|
||||
metadata.ExposureModes = append([]api.ExposureMode(nil), descriptor.ExposureModes...)
|
||||
metadata.DerivedCapabilities = append([]api.CaringDerivedCapability(nil), descriptor.DerivedCapabilities...)
|
||||
return metadata
|
||||
}
|
||||
|
||||
func decisionID(metadata api.PolicyPackageMetadata, request api.CheckRequest, envelope api.DecisionEnvelope) string {
|
||||
data, _ := json.Marshal(struct {
|
||||
PolicyID string `json:"policy_id"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Request api.CheckRequest `json:"request"`
|
||||
Effect api.DecisionEffect `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}{
|
||||
PolicyID: metadata.ID,
|
||||
PolicyVersion: metadata.Version,
|
||||
Request: request,
|
||||
Effect: envelope.Effect,
|
||||
Reason: envelope.Reason,
|
||||
})
|
||||
sum := sha256.Sum256(data)
|
||||
return "decision:" + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
func copyMap(in map[string]any) map[string]any {
|
||||
out := make(map[string]any, len(in))
|
||||
for key, value := range in {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// setAuthoritative writes a registry fact over whatever the request carried for
|
||||
// that key, and records the key when a caller value was displaced so the
|
||||
// override is visible in diagnostics rather than silent.
|
||||
func setAuthoritative(target map[string]any, key string, value any, scope string, overridden *[]string) {
|
||||
if isEmptyAttribute(value) {
|
||||
return
|
||||
}
|
||||
if existing, exists := target[key]; exists && overridden != nil && !equalAttribute(existing, value) {
|
||||
*overridden = append(*overridden, scope+"."+key)
|
||||
}
|
||||
target[key] = value
|
||||
}
|
||||
|
||||
func setAuthoritatives(target map[string]any, attrs map[string]any, scope string, overridden *[]string) {
|
||||
for _, key := range sortedKeys(attrs) {
|
||||
setAuthoritative(target, key, attrs[key], scope, overridden)
|
||||
}
|
||||
}
|
||||
|
||||
func equalAttribute(a, b any) bool {
|
||||
left, errLeft := json.Marshal(a)
|
||||
right, errRight := json.Marshal(b)
|
||||
if errLeft != nil || errRight != nil {
|
||||
return false
|
||||
}
|
||||
return bytes.Equal(left, right)
|
||||
}
|
||||
|
||||
func sortedKeys(attrs map[string]any) []string {
|
||||
keys := make([]string, 0, len(attrs))
|
||||
for key := range attrs {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func addAttributes(target map[string]any, attrs map[string]any) {
|
||||
for key, value := range attrs {
|
||||
addAttribute(target, key, value)
|
||||
}
|
||||
}
|
||||
|
||||
func addAttribute(target map[string]any, key string, value any) {
|
||||
if isEmptyAttribute(value) {
|
||||
return
|
||||
}
|
||||
if _, exists := target[key]; !exists {
|
||||
target[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
func resourceMatchesFilters(resource api.ResourceRef, filters map[string]any) bool {
|
||||
for key, want := range filters {
|
||||
var got any
|
||||
switch key {
|
||||
case "id":
|
||||
got = resource.ID
|
||||
case "type", "resource_type":
|
||||
got = resource.Type
|
||||
case "system":
|
||||
got = resource.System
|
||||
case "tenant":
|
||||
got = resource.Tenant
|
||||
default:
|
||||
got = resource.Attributes[key]
|
||||
}
|
||||
if !valuesEqual(got, want) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func valuesEqual(got, want any) bool {
|
||||
if reflect.DeepEqual(got, want) {
|
||||
return true
|
||||
}
|
||||
return fmt.Sprint(got) == fmt.Sprint(want)
|
||||
}
|
||||
|
||||
func explanationSummary(decision api.DecisionEnvelope) string {
|
||||
action, _ := decision.Diagnostics["action"].(string)
|
||||
actor := decision.Subject.ID
|
||||
capability := action
|
||||
plane := ""
|
||||
if decision.Caring != nil && decision.Caring.Descriptor != nil {
|
||||
descriptor := decision.Caring.Descriptor
|
||||
if descriptor.OrganizationRelation != "" || descriptor.CanonicalRole != "" {
|
||||
actor = strings.TrimSpace(fmt.Sprintf("%s %s", descriptor.OrganizationRelation, descriptor.CanonicalRole))
|
||||
}
|
||||
if len(descriptor.Capabilities) > 0 {
|
||||
capability = string(descriptor.Capabilities[0])
|
||||
}
|
||||
if len(descriptor.Planes) > 0 {
|
||||
plane = string(descriptor.Planes[0]) + " Plane "
|
||||
}
|
||||
}
|
||||
if capability == "" {
|
||||
capability = "access"
|
||||
}
|
||||
|
||||
verb := "may"
|
||||
switch decision.Effect {
|
||||
case api.DecisionEffectDeny:
|
||||
verb = "may not"
|
||||
case api.DecisionEffectRedact:
|
||||
verb = "receives redacted"
|
||||
case api.DecisionEffectAuditOnly:
|
||||
verb = "is audit-only for"
|
||||
case api.DecisionEffectNotApplicable:
|
||||
verb = "has no applicable policy for"
|
||||
}
|
||||
|
||||
reason := decision.Reason
|
||||
if reason == "" {
|
||||
reason = string(decision.Effect)
|
||||
}
|
||||
return fmt.Sprintf("%s %s %s %sresource %s because %s.", actor, verb, capability, plane, decision.Resource.ID, reason)
|
||||
}
|
||||
|
||||
func isEmptyAttribute(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return typed == ""
|
||||
case api.OrganizationRelation:
|
||||
return typed == ""
|
||||
case []api.CanonicalRole:
|
||||
return len(typed) == 0
|
||||
case []string:
|
||||
return len(typed) == 0
|
||||
default:
|
||||
return value == nil
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,257 @@
|
|||
module forgejo.org
|
||||
|
||||
go 1.24
|
||||
|
||||
toolchain go1.24.3
|
||||
|
||||
require (
|
||||
code.forgejo.org/f3/gof3/v3 v3.10.6
|
||||
code.forgejo.org/forgejo-contrib/go-libravatar v0.0.0-20191008002943-06d1c002b251
|
||||
code.forgejo.org/forgejo/levelqueue v1.0.0
|
||||
code.forgejo.org/forgejo/reply v1.0.2
|
||||
code.forgejo.org/go-chi/binding v1.0.0
|
||||
code.forgejo.org/go-chi/cache v1.0.0
|
||||
code.forgejo.org/go-chi/captcha v1.0.1
|
||||
code.forgejo.org/go-chi/session v1.0.1
|
||||
code.gitea.io/actions-proto-go v0.4.0
|
||||
code.gitea.io/sdk/gitea v0.20.0
|
||||
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570
|
||||
connectrpc.com/connect v1.17.0
|
||||
github.com/42wim/httpsig v1.2.2
|
||||
github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358
|
||||
github.com/ProtonMail/go-crypto v1.1.6
|
||||
github.com/PuerkitoBio/goquery v1.10.2
|
||||
github.com/SaveTheRbtz/zstd-seekable-format-go/pkg v0.7.2
|
||||
github.com/alecthomas/chroma/v2 v2.15.0
|
||||
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb
|
||||
github.com/blevesearch/bleve/v2 v2.5.2
|
||||
github.com/buildkite/terminal-to-html/v3 v3.16.8
|
||||
github.com/caddyserver/certmagic v0.22.2
|
||||
github.com/chi-middleware/proxy v1.1.1
|
||||
github.com/djherbis/buffer v1.2.0
|
||||
github.com/djherbis/nio/v3 v3.0.1
|
||||
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/editorconfig/editorconfig-core-go/v2 v2.6.3
|
||||
github.com/emersion/go-imap v1.2.1
|
||||
github.com/felixge/fgprof v0.9.5
|
||||
github.com/fsnotify/fsnotify v1.8.0
|
||||
github.com/gliderlabs/ssh v0.3.8
|
||||
github.com/go-ap/activitypub v0.0.0-20231114162308-e219254dc5c9
|
||||
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73
|
||||
github.com/go-chi/chi/v5 v5.2.0
|
||||
github.com/go-chi/cors v1.2.1
|
||||
github.com/go-co-op/gocron v1.37.0
|
||||
github.com/go-enry/go-enry/v2 v2.9.2
|
||||
github.com/go-git/go-git/v5 v5.13.2
|
||||
github.com/go-ldap/ldap/v3 v3.4.6
|
||||
github.com/go-openapi/spec v0.20.14
|
||||
github.com/go-sql-driver/mysql v1.9.1
|
||||
github.com/go-webauthn/webauthn v0.12.2
|
||||
github.com/gobwas/glob v0.2.3
|
||||
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f
|
||||
github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
|
||||
github.com/google/go-github/v64 v64.0.0
|
||||
github.com/google/pprof v0.0.0-20241017200806-017d972448fc
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/feeds v1.2.0
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
github.com/hashicorp/go-version v1.7.0
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7
|
||||
github.com/huandu/xstrings v1.5.0
|
||||
github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056
|
||||
github.com/jhillyerd/enmime/v2 v2.1.0
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
|
||||
github.com/klauspost/compress v1.17.11
|
||||
github.com/klauspost/cpuid/v2 v2.2.10
|
||||
github.com/lib/pq v1.10.9
|
||||
github.com/markbates/goth v1.80.0
|
||||
github.com/mattn/go-isatty v0.0.20
|
||||
github.com/mattn/go-sqlite3 v1.14.28
|
||||
github.com/meilisearch/meilisearch-go v0.31.0
|
||||
github.com/mholt/archiver/v3 v3.5.1
|
||||
github.com/microcosm-cc/bluemonday v1.0.27
|
||||
github.com/minio/minio-go/v7 v7.0.88
|
||||
github.com/msteinert/pam/v2 v2.1.0
|
||||
github.com/nektos/act v0.2.52
|
||||
github.com/niklasfasching/go-org v1.7.0
|
||||
github.com/olivere/elastic/v7 v7.0.32
|
||||
github.com/opencontainers/go-digest v1.0.0
|
||||
github.com/opencontainers/image-spec v1.1.1
|
||||
github.com/pquerna/otp v1.4.0
|
||||
github.com/prometheus/client_golang v1.21.1
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1
|
||||
github.com/sassoftware/go-rpmutils v0.4.0
|
||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3
|
||||
github.com/shurcooL/vfsgen v0.0.0-20230704071429-0000e147ea92
|
||||
github.com/stretchr/testify v1.10.0
|
||||
github.com/syndtr/goleveldb v1.0.0
|
||||
github.com/ulikunitz/xz v0.5.12
|
||||
github.com/urfave/cli/v2 v2.27.6
|
||||
github.com/valyala/fastjson v1.6.4
|
||||
github.com/yohcop/openid-go v1.0.1
|
||||
github.com/yuin/goldmark v1.7.8
|
||||
github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc
|
||||
gitlab.com/gitlab-org/api/client-go v0.126.0
|
||||
go.uber.org/mock v0.5.0
|
||||
golang.org/x/crypto v0.36.0
|
||||
golang.org/x/image v0.25.0
|
||||
golang.org/x/net v0.38.0
|
||||
golang.org/x/oauth2 v0.28.0
|
||||
golang.org/x/sync v0.12.0
|
||||
golang.org/x/sys v0.31.0
|
||||
golang.org/x/text v0.23.0
|
||||
google.golang.org/protobuf v1.36.4
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||
gopkg.in/ini.v1 v1.67.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
mvdan.cc/xurls/v2 v2.5.0
|
||||
xorm.io/builder v0.3.13
|
||||
xorm.io/xorm v1.3.9
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute/metadata v0.6.0 // indirect
|
||||
dario.cat/mergo v1.0.0 // indirect
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect
|
||||
github.com/DataDog/zstd v1.5.5 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/RoaringBitmap/roaring/v2 v2.4.5 // indirect
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.22.0 // indirect
|
||||
github.com/blevesearch/bleve_index_api v1.2.8 // indirect
|
||||
github.com/blevesearch/geo v0.2.3 // indirect
|
||||
github.com/blevesearch/go-faiss v1.0.25 // indirect
|
||||
github.com/blevesearch/go-porterstemmer v1.0.3 // indirect
|
||||
github.com/blevesearch/gtreap v0.1.1 // indirect
|
||||
github.com/blevesearch/mmap-go v1.0.4 // indirect
|
||||
github.com/blevesearch/scorch_segment_api/v2 v2.3.10 // indirect
|
||||
github.com/blevesearch/segment v0.9.1 // indirect
|
||||
github.com/blevesearch/snowballstem v0.9.0 // indirect
|
||||
github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect
|
||||
github.com/blevesearch/vellum v1.1.0 // indirect
|
||||
github.com/blevesearch/zapx/v11 v11.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v12 v12.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v13 v13.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v14 v14.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v15 v15.4.2 // indirect
|
||||
github.com/blevesearch/zapx/v16 v16.2.4 // indirect
|
||||
github.com/boombuler/barcode v1.0.1 // indirect
|
||||
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874 // indirect
|
||||
github.com/caddyserver/zerossl v0.1.3 // indirect
|
||||
github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudflare/circl v1.6.1 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
|
||||
github.com/cyphar/filepath-securejoin v0.3.6 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/davidmz/go-pageant v1.0.2 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dlclark/regexp2 v1.11.4 // indirect
|
||||
github.com/emersion/go-sasl v0.0.0-20231106173351-e73c9f7bad43 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/fatih/color v1.16.0 // indirect
|
||||
github.com/fxamacker/cbor/v2 v2.8.0 // indirect
|
||||
github.com/go-ap/errors v0.0.0-20231003111023-183eef4b31b7 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||
github.com/go-enry/go-oniguruma v1.2.1 // indirect
|
||||
github.com/go-fed/httpsig v1.1.0 // indirect
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.20.2 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.4 // indirect
|
||||
github.com/go-openapi/swag v0.22.7 // indirect
|
||||
github.com/go-webauthn/x v0.1.20 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/google/btree v1.1.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/go-tpm v0.9.3 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||
github.com/klauspost/pgzip v1.2.6 // indirect
|
||||
github.com/libdns/libdns v0.2.3 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
github.com/markbates/going v1.0.3 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mholt/acmez/v3 v3.1.1 // indirect
|
||||
github.com/miekg/dns v1.1.63 // indirect
|
||||
github.com/minio/crc64nvme v1.0.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mrjones/oauth v0.0.0-20190623134757-126b35219450 // indirect
|
||||
github.com/mschoch/smat v0.2.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/nwaples/rardecode v1.1.3 // indirect
|
||||
github.com/olekukonko/tablewriter v0.0.5 // indirect
|
||||
github.com/onsi/ginkgo v1.16.5 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.21 // indirect
|
||||
github.com/pjbgf/sha1cd v0.3.2 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.62.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/rhysd/actionlint v1.6.27 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/skeema/knownhosts v1.3.0 // indirect
|
||||
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
|
||||
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
|
||||
github.com/zeebo/assert v1.3.0 // indirect
|
||||
github.com/zeebo/blake3 v0.2.4 // indirect
|
||||
go.etcd.io/bbolt v1.4.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
go.uber.org/zap/exp v0.3.0 // indirect
|
||||
golang.org/x/mod v0.24.0 // indirect
|
||||
golang.org/x/time v0.10.0 // indirect
|
||||
golang.org/x/tools v0.31.0 // indirect
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
)
|
||||
|
||||
replace github.com/hashicorp/go-version => github.com/6543/go-version v1.3.1
|
||||
|
||||
replace github.com/shurcooL/vfsgen => github.com/lunny/vfsgen v0.0.0-20220105142115-2c99e1ffdfa0
|
||||
|
||||
replace github.com/nektos/act => code.forgejo.org/forgejo/act v1.25.1
|
||||
|
||||
replace github.com/mholt/archiver/v3 => code.forgejo.org/forgejo/archiver/v3 v3.5.1
|
||||
|
||||
replace github.com/gliderlabs/ssh => code.forgejo.org/forgejo/ssh v0.0.0-20241211213324-5fc306ca0616
|
||||
|
||||
replace git.sr.ht/~mariusor/go-xsd-duration => code.forgejo.org/forgejo/go-xsd-duration v0.0.0-20220703122237-02e73435a078
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,68 @@
|
|||
// Copyright 2021 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package oauth2
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/markbates/goth"
|
||||
"github.com/markbates/goth/gothic"
|
||||
)
|
||||
|
||||
// Callout redirects request/response pair to authenticate against the provider
|
||||
func (source *Source) Callout(request *http.Request, response http.ResponseWriter, codeChallengeS256 string) error {
|
||||
// not sure if goth is thread safe (?) when using multiple providers
|
||||
request.Header.Set(ProviderHeaderKey, source.authSource.Name)
|
||||
|
||||
var querySuffix string
|
||||
if codeChallengeS256 != "" {
|
||||
querySuffix = "&" + url.Values{
|
||||
"code_challenge_method": []string{"S256"},
|
||||
"code_challenge": []string{codeChallengeS256},
|
||||
}.Encode()
|
||||
}
|
||||
|
||||
// don't use the default gothic begin handler to prevent issues when some error occurs
|
||||
// normally the gothic library will write some custom stuff to the response instead of our own nice error page
|
||||
// gothic.BeginAuthHandler(response, request)
|
||||
|
||||
gothRWMutex.RLock()
|
||||
defer gothRWMutex.RUnlock()
|
||||
|
||||
url, err := gothic.GetAuthURL(response, request)
|
||||
if err == nil {
|
||||
// hacky way to set the code_challenge, but no better way until
|
||||
// https://github.com/markbates/goth/issues/516 is resolved
|
||||
http.Redirect(response, request, url+querySuffix, http.StatusTemporaryRedirect)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Callback handles OAuth callback, resolve to a goth user and send back to original url
|
||||
// this will trigger a new authentication request, but because we save it in the session we can use that
|
||||
func (source *Source) Callback(request *http.Request, response http.ResponseWriter, codeVerifier string) (goth.User, error) {
|
||||
// not sure if goth is thread safe (?) when using multiple providers
|
||||
request.Header.Set(ProviderHeaderKey, source.authSource.Name)
|
||||
|
||||
if codeVerifier != "" {
|
||||
// hacky way to set the code_verifier...
|
||||
// Will be picked up inside CompleteUserAuth: params := req.URL.Query()
|
||||
// https://github.com/markbates/goth/pull/474/files
|
||||
request = request.Clone(request.Context())
|
||||
q := request.URL.Query()
|
||||
q.Add("code_verifier", codeVerifier)
|
||||
request.URL.RawQuery = q.Encode()
|
||||
}
|
||||
|
||||
gothRWMutex.RLock()
|
||||
defer gothRWMutex.RUnlock()
|
||||
|
||||
user, err := gothic.CompleteUserAuth(response, request)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
{
|
||||
"pid": 5,
|
||||
"state": "running",
|
||||
"workspace": "/tmp/apps-pdp-actual-producer-q45xo6qu",
|
||||
"argv": [
|
||||
"/usr/bin/bwrap",
|
||||
"--unshare-net",
|
||||
"--unshare-pid",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--symlink",
|
||||
"usr/bin",
|
||||
"/bin",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--bind",
|
||||
"/tmp/apps-pdp-actual-producer-q45xo6qu",
|
||||
"/work",
|
||||
"--ro-bind",
|
||||
"/home/worsch/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.26.7.linux-amd64",
|
||||
"/toolchain",
|
||||
"--ro-bind",
|
||||
"/home/worsch/go/pkg/mod",
|
||||
"/modules",
|
||||
"--chdir",
|
||||
"/work/source",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"PATH",
|
||||
"/toolchain/bin:/usr/bin:/bin",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work/home",
|
||||
"--setenv",
|
||||
"GOPROXY",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOSUMDB",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOTOOLCHAIN",
|
||||
"local",
|
||||
"--setenv",
|
||||
"GOCACHE",
|
||||
"/work/gocache",
|
||||
"--setenv",
|
||||
"GOMODCACHE",
|
||||
"/modules",
|
||||
"--setenv",
|
||||
"GOMAXPROCS",
|
||||
"4",
|
||||
"--setenv",
|
||||
"CGO_ENABLED",
|
||||
"0",
|
||||
"--",
|
||||
"go",
|
||||
"test",
|
||||
"-p",
|
||||
"4",
|
||||
"-json",
|
||||
"./cmd/access-engine",
|
||||
"-run",
|
||||
"TestForgejoActualPolicySignedLosslessAndLegacy|TestTrustedServiceActualHTTPPositiveAndRefusals|TestTrustedServiceRetainedRegistryPreapprovalAndRefusals",
|
||||
"-count=1"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
BIN_DIR ?= bin
|
||||
BIN := $(BIN_DIR)/access-engine
|
||||
PKG := ./...
|
||||
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo 0.0.0-dev)
|
||||
LDFLAGS := -X main.version=$(VERSION)
|
||||
|
||||
.PHONY: all build test vet lint fmt tidy sbom clean ci overlay-render overlay-dry-run verify-posture check-layer
|
||||
|
||||
all: vet lint test build
|
||||
|
||||
build:
|
||||
@mkdir -p $(BIN_DIR)
|
||||
go build -ldflags "$(LDFLAGS)" -o $(BIN) ./cmd/access-engine
|
||||
|
||||
test: check-layer
|
||||
go test -race $(PKG)
|
||||
|
||||
check-layer:
|
||||
go run ./tools/check_layer_conformance.go
|
||||
|
||||
vet:
|
||||
go vet $(PKG)
|
||||
|
||||
fmt:
|
||||
gofmt -l -w .
|
||||
|
||||
tidy:
|
||||
go mod tidy
|
||||
|
||||
lint:
|
||||
@if command -v golangci-lint >/dev/null 2>&1; then \
|
||||
golangci-lint run $(PKG); \
|
||||
else \
|
||||
echo "golangci-lint not installed; run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"; \
|
||||
echo "falling back to: go vet"; \
|
||||
go vet $(PKG); \
|
||||
fi
|
||||
|
||||
GOBIN_PATH := $(shell go env GOPATH)/bin
|
||||
|
||||
sbom:
|
||||
@mkdir -p $(BIN_DIR)
|
||||
@if command -v cyclonedx-gomod >/dev/null 2>&1; then \
|
||||
cyclonedx-gomod mod -json -output $(BIN_DIR)/sbom.cdx.json .; \
|
||||
echo "SBOM written to $(BIN_DIR)/sbom.cdx.json (cyclonedx-gomod)"; \
|
||||
elif [ -x "$(GOBIN_PATH)/cyclonedx-gomod" ]; then \
|
||||
"$(GOBIN_PATH)/cyclonedx-gomod" mod -json -output $(BIN_DIR)/sbom.cdx.json .; \
|
||||
echo "SBOM written to $(BIN_DIR)/sbom.cdx.json (cyclonedx-gomod via GOPATH)"; \
|
||||
elif command -v syft >/dev/null 2>&1; then \
|
||||
syft . -o cyclonedx-json=$(BIN_DIR)/sbom.cdx.json; \
|
||||
echo "SBOM written to $(BIN_DIR)/sbom.cdx.json (syft)"; \
|
||||
else \
|
||||
echo "no SBOM tool found. install one:"; \
|
||||
echo " go install github.com/CycloneDX/cyclonedx-gomod/cmd/cyclonedx-gomod@latest"; \
|
||||
echo " or syft: https://github.com/anchore/syft"; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
clean:
|
||||
rm -rf $(BIN_DIR)
|
||||
|
||||
ci: vet lint test build overlay-render
|
||||
|
||||
verify-posture:
|
||||
@bash tools/verify-posture.sh
|
||||
|
||||
.PHONY: verify-emission-cadence
|
||||
verify-emission-cadence:
|
||||
python3 tools/verify_emission_cadence.py
|
||||
|
||||
overlay-render:
|
||||
@tests/stage1.sh
|
||||
|
||||
overlay-dry-run:
|
||||
@test -n "$$KUBECONFIG" || { echo "set KUBECONFIG to the railiance01 kubeconfig"; exit 1; }
|
||||
@for values in values/stage2-canary.yaml values/user-engine.yaml values/tenant-engine.yaml; do \
|
||||
echo "server-dry-run $$values"; \
|
||||
helm template flex-auth charts/flex-auth -f "$$values" --namespace flex-auth \
|
||||
| kubectl apply --dry-run=server --server-side -f -; \
|
||||
done
|
||||
|
||||
.PHONY: decisionpep-export decisionpep-check
|
||||
decisionpep-export:
|
||||
python3 tools/export_decisionpep_adapter.py
|
||||
|
||||
decisionpep-check:
|
||||
python3 tools/export_decisionpep_adapter.py --check
|
||||
go test ./pkg/decisionpep
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
# Target Revenue Source License
|
||||
|
||||
**Version 1.0, Candidate 1 (V1C1)**
|
||||
|
||||
---
|
||||
|
||||
> **PRELIMINARY CANDIDATE — SUBJECT TO CHANGE — NOT FINAL**
|
||||
>
|
||||
> This repository is governed by the Target Revenue Source License
|
||||
> (TRSL), Version 1, Candidate 1. This is the framework's first working
|
||||
> candidate, adopted as the org's preliminary operating license across
|
||||
> all repos (maintainer decision, 2026-07-29) during the build/alpha
|
||||
> stage — see `SCOPE.md` §1 and Appendix A of the canonical text (link
|
||||
> below) for the alpha/beta risk-acceptance decision this reflects and
|
||||
> what it does and does not mean. Full specialist legal review is
|
||||
> explicitly deferred until the framework moves out of beta.
|
||||
>
|
||||
> **Canonical source, full candidate-status banner, and Appendix A
|
||||
> (non-normative candidate notes tracking every open item):** the
|
||||
> `coulomb` org's `target-revenue` repository,
|
||||
> `specs/TargetRevenueSourceLicense-V1C1.md` — this file is the operative
|
||||
> legal text (Preamble through Section 11) only; the canonical document
|
||||
> is authoritative if this copy and that document ever diverge.
|
||||
|
||||
---
|
||||
|
||||
## Preamble
|
||||
|
||||
This Target Revenue Source License ("**License**") governs the Software identified in the applicable Phase Manifest. It implements the Target Revenue Framework: a defined development Phase accumulates Development Credit and Remission Credit against an immutable Initial Target until the Milestone Release automatically and irrevocably converts to a declared permissive Future License.
|
||||
|
||||
Commercial beneficiaries fund the creation and early availability of a software improvement; once the declared target is satisfied, the governed release becomes permissively open source.
|
||||
|
||||
## 1. Definitions
|
||||
|
||||
Capitalized terms used in this License have the meanings given below. Where a term is also defined in the Phase Manifest or Target Ledger for a specific Phase, the Phase Manifest and Target Ledger govern the *values* (amounts, dates, identifiers) and this License governs the *legal effect* of those values — the two must not be read as conflicting definitions of the same concept.
|
||||
|
||||
**"Commercial Entitlement"** means a right, purchased or otherwise granted under a Commercial Use Agreement, to make Commercial Use of the Software during a Phase.
|
||||
|
||||
**"Commercial Use"** means billing, invoicing, or otherwise charging any customer a fee, subscription, license fee, or other consideration for or in connection with use of the Software, at any time before the Conversion Event for the applicable Phase, regardless of whether the person or organization billed would otherwise qualify for Noncommercial Use. Commercial Use occurs by virtue of such billing alone, whether or not the resulting payment is registered with the Trust Service; in particular, billing a customer for pre-conversion use of the Software without recording the corresponding payment in the applicable Phase's Target Ledger is Commercial Use without a valid Commercial Entitlement — a violation of Section 3, addressed under Section 7 and, where applicable, the Enforcement Network described in the canonical repository's `specs/EnforcementNetworkConcept.md`.
|
||||
|
||||
**"Commercial Use Agreement"** means the separate agreement, referenced by the applicable Phase Manifest, under which a Commercial Entitlement is purchased or granted. This License does not itself set pricing, metering, or payment terms — those are governed by the Commercial Use Agreement.
|
||||
|
||||
**"Conversion Event"** means the moment the Outstanding Target for a Phase reaches zero, as computed from the Phase Manifest and Target Ledger per the Target Ledger Specification. The Conversion Event occurs automatically and is not conditioned on any declaration, attestation, or other act by the Licensor or any Trust Service.
|
||||
|
||||
**"Development Credit"** means the portion of a collected and settled payment explicitly allocated toward satisfying the Initial Target of a specific Phase, as recorded in that Phase's Target Ledger.
|
||||
|
||||
**"Future License"** means the permissive license identified in the applicable Phase Manifest, being either the MIT License or the Apache License, Version 2.0, which applies to the Milestone Release upon the Conversion Event.
|
||||
|
||||
**"Initial Target"** means the immutable monetary target declared for a Phase in its Phase Manifest.
|
||||
|
||||
**"Licensor"** means **Binky Hedgehog GmbH**, the party that publishes the Phase Manifest and holds the rights necessary to grant this License and the Future License for the Milestone Release.
|
||||
|
||||
**"Milestone Release"** means the precisely identified software release designated in the applicable Phase Manifest, identified by an immutable source revision, release artifact, or cryptographic digest.
|
||||
|
||||
**"Noncommercial Use"** means use of the Software for personal purposes, private study, hobby or amateur projects; use by any charitable organization, educational institution, public research organization, or government institution acting in a non-revenue-generating capacity; or other use of a materially similar character.
|
||||
|
||||
**"Outstanding Target"** means, at any time, `max(0, Initial Target − cumulative Development Credit − cumulative Remission Credit)` for a Phase, as computed from that Phase's Target Ledger.
|
||||
|
||||
**"Phase"** means a bounded development undertaking governed by one Initial Target, one Milestone Release, one degeneration policy, and one Future License declaration, as declared in a Phase Manifest.
|
||||
|
||||
**"Phase Manifest"** means the published, immutable declaration identifying a Phase, its Milestone Release, Initial Target, Future License, degeneration policy, and Target Ledger location, as specified in the Phase Manifest Specification.
|
||||
|
||||
**"Remission Credit"** means a transparent, non-revenue reduction of a Phase's Outstanding Target, generated under that Phase's published degeneration policy and recorded in the Target Ledger.
|
||||
|
||||
**"Settled Payment"** means a payment that has cleared through its payment processor and is no longer subject to reversal in the ordinary course (chargeback, dispute, or equivalent), as further specified by the applicable Commercial Use Agreement or monetization extension.
|
||||
|
||||
**"Software"** means the source code, object code, and associated documentation of the Milestone Release identified in the applicable Phase Manifest.
|
||||
|
||||
**"Target Ledger"** means the append-only record of Development Credit, Remission Credit, and correction entries for a Phase, as specified in the Target Ledger Specification.
|
||||
|
||||
**"You"** or **"Licensee"** means the individual or entity exercising rights under this License.
|
||||
|
||||
## 2. Grant of Rights for Noncommercial Use
|
||||
|
||||
Subject to the terms of this License, the Licensor grants You a worldwide, royalty-free, non-exclusive license, during the applicable Phase, to:
|
||||
|
||||
(a) use, reproduce, and study the Software for any Noncommercial Use;
|
||||
|
||||
(b) modify the Software and create derivative works of it for any Noncommercial Use; and
|
||||
|
||||
(c) redistribute the Software and Your modifications, in source or object form, for any Noncommercial Use, provided that You include this License, unmodified, with any such redistribution, and that You do not remove or alter any copyright, patent, trademark, or attribution notices contained in the Software.
|
||||
|
||||
This grant does not extend to Commercial Use. Commercial Use requires a Commercial Entitlement under Section 3.
|
||||
|
||||
## 3. Commercial Use
|
||||
|
||||
You may not make Commercial Use of the Software during the applicable Phase unless You hold a valid, current Commercial Entitlement under a Commercial Use Agreement with the Licensor covering the applicable Phase. A Commercial Entitlement granted under one Phase's Commercial Use Agreement does not extend to a later Phase's Milestone Release unless the Commercial Use Agreement expressly says so.
|
||||
|
||||
This Section 3 states the existence and boundary of the commercial-use restriction. It does not itself set pricing, invoicing, metering, audit rights, or payment terms — those are governed exclusively by the applicable Commercial Use Agreement.
|
||||
|
||||
## 4. Patent License
|
||||
|
||||
Subject to the terms of this License, each contributor to the Software grants You, during the applicable Phase and solely to the extent of rights granted under Sections 2 and 3, a perpetual (subject to the termination below), worldwide, non-exclusive, no-charge, royalty-free patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Software, limited to those patent claims licensable by that contributor that are necessarily infringed by their contribution(s) alone or by combination of their contribution(s) with the Software.
|
||||
|
||||
If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Software or a contribution incorporated within it constitutes direct or contributory patent infringement, then any patent licenses granted to You under this Section 4 for the Software shall terminate as of the date such litigation is filed.
|
||||
|
||||
## 5. Automatic Conversion to the Future License
|
||||
|
||||
**5.1 Automatic effect.** Upon the Conversion Event for a Phase, the rights and restrictions in Sections 3 (Commercial Use) of this License, as they apply to that Phase's Milestone Release, terminate automatically. In their place, the Milestone Release is licensed under the Future License identified in that Phase's Phase Manifest, effective as of the Conversion Event, without any further act, declaration, or attestation required by the Licensor, any Trust Service, or any other party.
|
||||
|
||||
**5.2 Irrevocability.** Once a valid Conversion Event has occurred for a Phase, no subsequent refund, chargeback, accounting correction, dispute, or termination of this License for an unrelated breach shall revoke, suspend, or otherwise impair the Future License grant for that Phase's Milestone Release. Any shortfall or dispute arising after a Conversion Event is a commercial or accounting matter between the relevant parties and does not reinstate a commercial-use restriction over already-converted Software.
|
||||
|
||||
**5.3 Prior freedom preserved.** A later Phase covering subsequent improvements to the Software does not restrict, withdraw, or otherwise affect the rights granted under the Future License for an earlier Phase's already-converted Milestone Release.
|
||||
|
||||
**5.4 Evidence, not cause.** A Trust Service may publish a Conversion Attestation documenting a Conversion Event. Such an attestation is evidence that the Conversion Event occurred; it is not a condition of, and its absence or delay does not postpone, the automatic effect described in Section 5.1. Any person may independently verify whether a Conversion Event has occurred directly from the Phase Manifest and Target Ledger.
|
||||
|
||||
## 6. Successive Phases
|
||||
|
||||
The Licensor may declare a new Phase covering subsequent improvements to the Software following a Milestone Release's Conversion Event. Each Phase is independently governed by its own Phase Manifest, Initial Target, degeneration policy, and Target Ledger. Nothing in a later Phase's Phase Manifest may be construed to reduce or withdraw rights already granted under Section 5 for an earlier Phase's Milestone Release.
|
||||
|
||||
## 7. Term and Termination
|
||||
|
||||
**7.1 Term.** This License applies to the Software for the duration of the applicable Phase, and, for the Milestone Release, indefinitely following that Phase's Conversion Event under the Future License.
|
||||
|
||||
**7.2 Termination for breach.** If You breach Section 3 (Commercial Use) or Section 2(c) (redistribution notice requirement), the Licensor may terminate this License as to You. Before such termination becomes effective, the Licensor shall provide You written notice of the breach; if You cure the breach within thirty (30) days of that notice, this License continues in effect. A second breach of the same provision within twelve (12) months may be terminated immediately without a further cure opportunity.
|
||||
|
||||
**7.3 Effect of termination.** Termination under this Section 7 affects only Your rights under Sections 2 and 3 for the Phase in which the breach occurred. It does not affect any rights already vested under Section 5 (Automatic Conversion) for a Milestone Release whose Conversion Event has already occurred, per Section 5.2.
|
||||
|
||||
**7.4 Public record of breach and resolution.** The Licensor shall cause the Trust Service to publish, as part of the public record for the affected Phase, notice of: (a) any breach notice issued under Section 7.2, stating the general nature of the breach and the date of notice; (b) whether the breach was cured within the applicable cure period, and the date of cure; and (c) any termination determination made under this Section 7, including its effective date and scope. This public record exists to give the ecosystem a transparent, verifiable conformity signal for the Phase, distinct from and in addition to the Development Credit and Remission Credit facts already published under Section 5.4 and the Target Ledger Specification.
|
||||
|
||||
A breach that You dispute, and that has not been finally determined, shall be recorded as **alleged**; it shall be recorded as **determined** only once the cure period has run without cure, or the dispute has been resolved against You under the applicable Commercial Use Agreement's dispute process, if any. The Trust Service shall update the record promptly upon resolution in either direction. Recording an alleged or determined breach under this Section 7.4 is a ministerial act of publishing the Licensor's determination (or a dispute process's outcome); it does not give the Trust Service discretionary authority to decide whether a breach occurred, consistent with Section 5.4's evidence-not-cause principle.
|
||||
|
||||
Whether, and under what conditions, the public record identifies a Commercial Entitlement holder by name is governed exclusively by the applicable Commercial Use Agreement, which the Licensor and that Commercial Entitlement holder negotiate and agree to directly. This License does not itself set a naming default. Where no Commercial Use Agreement addresses the question, or where the affected party has no Commercial Use Agreement at all (for example, a Section 2(c) breach by a Noncommercial Use licensee), the public record states the Phase and breach category only, without naming the party.
|
||||
|
||||
## 8. Disclaimer of Warranty
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. THE LICENSOR DOES NOT WARRANT THAT THE SOFTWARE WILL BE ERROR-FREE OR THAT ANY PHASE WILL REACH ITS CONVERSION EVENT.
|
||||
|
||||
## 9. Limitation of Liability
|
||||
|
||||
IN NO EVENT SHALL THE LICENSOR OR ANY CONTRIBUTOR BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE, EXCEPT TO THE EXTENT SUCH LIMITATION IS PROHIBITED BY APPLICABLE LAW.
|
||||
|
||||
## 10. Trademarks
|
||||
|
||||
This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary attribution.
|
||||
|
||||
## 11. General Provisions
|
||||
|
||||
**11.1 Governing law and venue.** Adopted for alpha/beta 2026-07-29: disputes arising under this License shall be resolved by binding arbitration, seated at a neutral, arbitration-mature venue (Singapore or London are the two candidates concretely supported by current research), rather than by litigation in a national court. The specific arbitral institution and substantive governing law remain a per-deployment blank pending final selection; they are not fixed by this candidate. See the canonical repository's `history/260729-TRSL-Jurisdiction-Synthesis.md` §2.
|
||||
|
||||
**11.2 Severability.** If any provision of this License is held unenforceable, the remaining provisions remain in full force, and the unenforceable provision shall be reformed to the minimum extent necessary to make it enforceable.
|
||||
|
||||
**11.3 No waiver.** Failure to enforce any provision of this License is not a waiver of future enforcement of that or any other provision.
|
||||
|
||||
**11.4 Entire agreement (as to licensing).** This License, together with the applicable Phase Manifest and, where applicable, the Commercial Use Agreement, constitutes the entire agreement between You and the Licensor regarding the Software's licensing terms. Operations, service, and consulting arrangements are governed by separate agreements, if any, and are not part of this License.
|
||||
|
||||
**11.5 Definitions control.** Marketing materials, documentation, or other non-normative communications about the Software must not describe pre-Conversion-Event Software as "Open Source," "free software," or "open core." Pre-conversion Noncommercial Use is **source-available**; pre-conversion Commercial Use requires a **Commercial Entitlement**; only post-conversion Software may be described as Open Source, under the Future License.
|
||||
|
||||
---
|
||||
|
||||
**No Phase is currently declared for this repository under this License.** Until a Phase Manifest is published and registered with the Trust Service for a Milestone Release in this repository, Sections 2–7 above have no operative subject matter here — this License establishes the governing framework in advance of that declaration, consistent with the org-wide rollout decision recorded in `target-revenue`'s `workplans/TREV-WP-0008-governance-and-pilot-rollout.md`.
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
module github.com/netkingdom/access-engine
|
||||
|
||||
go 1.24
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
// Package sign attaches a detached Ed25519 signature to a decision envelope
|
||||
// (FLEX-WP-0024). The signed material is json.Marshal of the envelope with
|
||||
// the signature field omitted.
|
||||
package sign
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
const AlgorithmEd25519 = "ed25519"
|
||||
|
||||
// CanonicalBytes is the exact payload that is signed and verified: the
|
||||
// envelope as emitted, with signature absent.
|
||||
func CanonicalBytes(envelope api.DecisionEnvelope) ([]byte, error) {
|
||||
envelope.Signature = nil
|
||||
data, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal canonical envelope: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func Sign(envelope *api.DecisionEnvelope, private ed25519.PrivateKey, kid string) error {
|
||||
if envelope == nil {
|
||||
return fmt.Errorf("envelope is required")
|
||||
}
|
||||
if len(private) != ed25519.PrivateKeySize {
|
||||
return fmt.Errorf("ed25519 private key has length %d", len(private))
|
||||
}
|
||||
if kid == "" {
|
||||
return fmt.Errorf("kid is required")
|
||||
}
|
||||
payload, err := CanonicalBytes(*envelope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sig := ed25519.Sign(private, payload)
|
||||
envelope.Signature = &api.EnvelopeSignature{
|
||||
Mode: api.EnvelopeSignatureSigned,
|
||||
Alg: AlgorithmEd25519,
|
||||
Kid: kid,
|
||||
Value: base64.RawURLEncoding.EncodeToString(sig),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Verify(envelope api.DecisionEnvelope, keys map[string]ed25519.PublicKey) error {
|
||||
sig := envelope.Signature
|
||||
if sig == nil || sig.Mode != api.EnvelopeSignatureSigned {
|
||||
return fmt.Errorf("envelope is not signed")
|
||||
}
|
||||
if sig.Alg != AlgorithmEd25519 {
|
||||
return fmt.Errorf("unsupported signature alg %q", sig.Alg)
|
||||
}
|
||||
pub, ok := keys[sig.Kid]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown signature kid %q", sig.Kid)
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(sig.Value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode signature: %w", err)
|
||||
}
|
||||
payload, err := CanonicalBytes(envelope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ed25519.Verify(pub, payload, raw) {
|
||||
return fmt.Errorf("signature does not match envelope")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DecodeEnvelope preserves JSON numeric kinds/lexemes emitted by task inputs.
|
||||
// Legacy producer envelopes remain byte-compatible. It does not invent another
|
||||
// signature canonicalization: CanonicalBytes still calls typed json.Marshal.
|
||||
func DecodeEnvelope(raw []byte) (api.DecisionEnvelope, error) {
|
||||
var envelope api.DecisionEnvelope
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&envelope); err != nil {
|
||||
return envelope, err
|
||||
}
|
||||
if _, err := decoder.Token(); err != io.EOF {
|
||||
return api.DecisionEnvelope{}, fmt.Errorf("trailing envelope data")
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,699 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ProtectedSystemManifest describes a system that delegates authorization to
|
||||
// flex-auth.
|
||||
type ProtectedSystemManifest struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name,omitempty" yaml:"name,omitempty"`
|
||||
Description string `json:"description,omitempty" yaml:"description,omitempty"`
|
||||
ClientBinding *ClientBinding `json:"client_binding,omitempty" yaml:"client_binding,omitempty"`
|
||||
ResourceTypes []ResourceType `json:"resource_types,omitempty" yaml:"resource_types,omitempty"`
|
||||
Actions []ActionDefinition `json:"actions,omitempty" yaml:"actions,omitempty"`
|
||||
CaringProfiles []string `json:"caring_profiles,omitempty" yaml:"caring_profiles,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// ClientBinding names the key-cape client a protected system's users sign in
|
||||
// through. It is descriptive only: the readback registry projection lists it,
|
||||
// and it never decides an allow (FLEX-DEC-2026-019).
|
||||
type ClientBinding struct {
|
||||
Issuer string `json:"issuer" yaml:"issuer"`
|
||||
ClientID string `json:"client_id" yaml:"client_id"`
|
||||
}
|
||||
|
||||
// ResourceType describes a resource namespace entry owned by a protected system.
|
||||
type ResourceType struct {
|
||||
Name string `json:"name" yaml:"name"`
|
||||
ParentTypes []string `json:"parent_types,omitempty" yaml:"parent_types,omitempty"`
|
||||
ScopeLevel ScopeLevel `json:"scope_level,omitempty" yaml:"scope_level,omitempty"`
|
||||
Planes []Plane `json:"planes,omitempty" yaml:"planes,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// ActionDefinition maps a protected-system action to CARING capabilities.
|
||||
type ActionDefinition struct {
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Capabilities []Capability `json:"capabilities,omitempty" yaml:"capabilities,omitempty"`
|
||||
Planes []Plane `json:"planes,omitempty" yaml:"planes,omitempty"`
|
||||
ExposureModes []ExposureMode `json:"exposure_modes,omitempty" yaml:"exposure_modes,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// SubjectManifest declares subjects, groups, teams, and tenants for local
|
||||
// registry loading.
|
||||
type SubjectManifest struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Subjects []Subject `json:"subjects,omitempty" yaml:"subjects,omitempty"`
|
||||
Groups []Group `json:"groups,omitempty" yaml:"groups,omitempty"`
|
||||
Teams []Team `json:"teams,omitempty" yaml:"teams,omitempty"`
|
||||
Tenants []Tenant `json:"tenants,omitempty" yaml:"tenants,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Subject is a human, service, automation, agent, or other acting identity.
|
||||
type Subject struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Type SubjectType `json:"type" yaml:"type"`
|
||||
DisplayName string `json:"display_name,omitempty" yaml:"display_name,omitempty"`
|
||||
OrganizationRelation OrganizationRelation `json:"organization_relation,omitempty" yaml:"organization_relation,omitempty"`
|
||||
Roles []CanonicalRole `json:"roles,omitempty" yaml:"roles,omitempty"`
|
||||
Groups []string `json:"groups,omitempty" yaml:"groups,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Claims map[string]any `json:"claims,omitempty" yaml:"claims,omitempty"`
|
||||
CaringDescriptors []CaringAccessDescriptor `json:"caring_descriptors,omitempty" yaml:"caring_descriptors,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Group is an assignment convenience, not a canonical role.
|
||||
type Group struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
DisplayName string `json:"display_name,omitempty" yaml:"display_name,omitempty"`
|
||||
Members []string `json:"members,omitempty" yaml:"members,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
CaringDescriptors []CaringAccessDescriptor `json:"caring_descriptors,omitempty" yaml:"caring_descriptors,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Team is a group-like ownership unit used by protected systems.
|
||||
type Team struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
DisplayName string `json:"display_name,omitempty" yaml:"display_name,omitempty"`
|
||||
Members []string `json:"members,omitempty" yaml:"members,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
CaringDescriptors []CaringAccessDescriptor `json:"caring_descriptors,omitempty" yaml:"caring_descriptors,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Tenant is a structural isolation boundary.
|
||||
type Tenant struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name,omitempty" yaml:"name,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// RelationshipFact records a relation between subjects, groups, teams, tenants,
|
||||
// and resources.
|
||||
type RelationshipFact struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
System string `json:"system,omitempty" yaml:"system,omitempty"`
|
||||
Subject string `json:"subject" yaml:"subject"`
|
||||
Relation string `json:"relation" yaml:"relation"`
|
||||
Object string `json:"object" yaml:"object"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Conditions []Condition `json:"conditions,omitempty" yaml:"conditions,omitempty"`
|
||||
Caring *CaringAccessDescriptor `json:"caring,omitempty" yaml:"caring,omitempty"`
|
||||
Provenance map[string]any `json:"provenance,omitempty" yaml:"provenance,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// PolicyPackageMetadata is the frontmatter contract for Rego-in-Markdown
|
||||
// policy packages.
|
||||
type PolicyPackageMetadata struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name,omitempty" yaml:"name,omitempty"`
|
||||
Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
|
||||
Version string `json:"version" yaml:"version"`
|
||||
Status string `json:"status,omitempty" yaml:"status,omitempty"`
|
||||
Package string `json:"package" yaml:"package"`
|
||||
Actions []string `json:"actions,omitempty" yaml:"actions,omitempty"`
|
||||
Owner string `json:"owner,omitempty" yaml:"owner,omitempty"`
|
||||
Fixtures []string `json:"fixtures,omitempty" yaml:"fixtures,omitempty"`
|
||||
Caring CaringPolicyMetadata `json:"caring" yaml:"caring"`
|
||||
Activation map[string]any `json:"activation,omitempty" yaml:"activation,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
// AllowTTL is a Go duration (for example "15m") that bounds every allow
|
||||
// this package produces. Omit to use DefaultAllowTTL. "none" or "0s"
|
||||
// means no stated end; the engine denies those allows (§9.7.1).
|
||||
AllowTTL string `json:"allow_ttl,omitempty" yaml:"allow_ttl,omitempty"`
|
||||
}
|
||||
|
||||
// CaringPolicyMetadata declares the CARING envelope a policy governs.
|
||||
type CaringPolicyMetadata struct {
|
||||
Profile string `json:"profile" yaml:"profile"`
|
||||
Enforce bool `json:"enforce,omitempty" yaml:"enforce,omitempty"`
|
||||
CanonicalRoles []CanonicalRole `json:"canonical_roles,omitempty" yaml:"canonical_roles,omitempty"`
|
||||
OrganizationRelations []OrganizationRelation `json:"organization_relations,omitempty" yaml:"organization_relations,omitempty"`
|
||||
Scopes []CaringScope `json:"scopes,omitempty" yaml:"scopes,omitempty"`
|
||||
Planes []Plane `json:"planes,omitempty" yaml:"planes,omitempty"`
|
||||
Capabilities []Capability `json:"capabilities,omitempty" yaml:"capabilities,omitempty"`
|
||||
ExposureModes []ExposureMode `json:"exposure_modes,omitempty" yaml:"exposure_modes,omitempty"`
|
||||
Conditions []Condition `json:"conditions,omitempty" yaml:"conditions,omitempty"`
|
||||
Restrictions []Restriction `json:"restrictions,omitempty" yaml:"restrictions,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// PolicyFixture binds a check request to an expected decision.
|
||||
type PolicyFixture struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Request CheckRequest `json:"request" yaml:"request"`
|
||||
Expect DecisionExpectation `json:"expect" yaml:"expect"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// DecisionExpectation is the compact fixture expectation for policy tests.
|
||||
type DecisionExpectation struct {
|
||||
Effect DecisionEffect `json:"effect" yaml:"effect"`
|
||||
Reason string `json:"reason,omitempty" yaml:"reason,omitempty"`
|
||||
Obligations []Obligation `json:"obligations,omitempty" yaml:"obligations,omitempty"`
|
||||
ConformanceFindings []CaringConformanceFinding `json:"conformance_findings,omitempty" yaml:"conformance_findings,omitempty"`
|
||||
}
|
||||
|
||||
// CheckRequest is the stable protected-system-facing decision request.
|
||||
type CheckRequest struct {
|
||||
ID string `json:"id,omitempty" yaml:"id,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Subject SubjectRef `json:"subject" yaml:"subject"`
|
||||
Action string `json:"action" yaml:"action"`
|
||||
Resource ResourceRef `json:"resource" yaml:"resource"`
|
||||
Context map[string]any `json:"context,omitempty" yaml:"context,omitempty"`
|
||||
CaringContext *CaringAccessDescriptor `json:"caring_context,omitempty" yaml:"caring_context,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty" yaml:"policy_version,omitempty"`
|
||||
|
||||
// Purpose is empty on every enforcement request. The readback pin sets it
|
||||
// to PurposeReadback, and it is hashed into every request digest, so an
|
||||
// advisory readback decision can never pass a PEP's §6.4.2 replay test for
|
||||
// an enforcement request (FLEX-DEC-2026-019). /v1/check and /v1/batch_check
|
||||
// refuse a request that carries it.
|
||||
Purpose string `json:"purpose,omitempty" yaml:"purpose,omitempty"`
|
||||
}
|
||||
|
||||
// PurposeReadback marks an advisory application-access readback decision.
|
||||
const PurposeReadback = "readback"
|
||||
|
||||
// BatchCheckRequest evaluates one subject/action against multiple resources.
|
||||
type BatchCheckRequest struct {
|
||||
ID string `json:"id,omitempty" yaml:"id,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Subject SubjectRef `json:"subject" yaml:"subject"`
|
||||
Action string `json:"action" yaml:"action"`
|
||||
Resources []ResourceRef `json:"resources" yaml:"resources"`
|
||||
Context map[string]any `json:"context,omitempty" yaml:"context,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty" yaml:"policy_version,omitempty"`
|
||||
}
|
||||
|
||||
// SubjectRef is a normalized subject reference in request and decision shapes.
|
||||
type SubjectRef struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Type SubjectType `json:"type,omitempty" yaml:"type,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Attributes map[string]any `json:"attributes,omitempty" yaml:"attributes,omitempty"`
|
||||
}
|
||||
|
||||
// ResourceRef is a normalized resource reference in request and decision shapes.
|
||||
type ResourceRef struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Type string `json:"type,omitempty" yaml:"type,omitempty"`
|
||||
System string `json:"system,omitempty" yaml:"system,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Attributes map[string]any `json:"attributes,omitempty" yaml:"attributes,omitempty"`
|
||||
}
|
||||
|
||||
// DecisionEffect is the stable decision outcome vocabulary.
|
||||
type DecisionEffect string
|
||||
|
||||
const (
|
||||
DecisionEffectAllow DecisionEffect = "allow"
|
||||
DecisionEffectDeny DecisionEffect = "deny"
|
||||
DecisionEffectRedact DecisionEffect = "redact"
|
||||
DecisionEffectAuditOnly DecisionEffect = "audit_only"
|
||||
DecisionEffectNotApplicable DecisionEffect = "not_applicable"
|
||||
)
|
||||
|
||||
// DecisionEffects returns the complete effect vocabulary. Every effect is an
|
||||
// emission class in cadence.yaml; a test fails if a constant above is missing
|
||||
// here, so a new effect cannot ship unclassified (FLEX-WP-0031-T03).
|
||||
func DecisionEffects() []DecisionEffect {
|
||||
return []DecisionEffect{
|
||||
DecisionEffectAllow,
|
||||
DecisionEffectDeny,
|
||||
DecisionEffectRedact,
|
||||
DecisionEffectAuditOnly,
|
||||
DecisionEffectNotApplicable,
|
||||
}
|
||||
}
|
||||
|
||||
// Restricts reports whether an effect withholds authority. This classification
|
||||
// does not exempt an effect from required durable emission (GH-DEC-2026-024).
|
||||
func (e DecisionEffect) Restricts() bool {
|
||||
switch e {
|
||||
case DecisionEffectDeny, DecisionEffectRedact, DecisionEffectNotApplicable:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DecisionRecordContractV1 is the published decision-record contract identifier.
|
||||
const DecisionRecordContractV1 = "flex-auth.decision-record.v1"
|
||||
|
||||
// DecisionEnvelope is the stable response produced by standalone and delegated
|
||||
// evaluators. It is flex-auth's published decision-record contract (§17).
|
||||
type DecisionEnvelope struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
ContractVersion string `json:"contract_version,omitempty" yaml:"contract_version,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty" yaml:"request_id,omitempty"`
|
||||
Effect DecisionEffect `json:"effect" yaml:"effect"`
|
||||
Reason string `json:"reason,omitempty" yaml:"reason,omitempty"`
|
||||
MatchedPolicyVersion string `json:"matched_policy_version,omitempty" yaml:"matched_policy_version,omitempty"`
|
||||
MatchedRule string `json:"matched_rule,omitempty" yaml:"matched_rule,omitempty"`
|
||||
Resource ResourceRef `json:"resource" yaml:"resource"`
|
||||
Subject SubjectRef `json:"subject" yaml:"subject"`
|
||||
Binding *DecisionBinding `json:"binding,omitempty" yaml:"binding,omitempty"`
|
||||
Lifetime *DecisionLifetime `json:"lifetime,omitempty" yaml:"lifetime,omitempty"`
|
||||
Obligations []Obligation `json:"obligations,omitempty" yaml:"obligations,omitempty"`
|
||||
Diagnostics map[string]any `json:"diagnostics,omitempty" yaml:"diagnostics,omitempty"`
|
||||
Provenance DecisionProvenance `json:"provenance" yaml:"provenance"`
|
||||
Signature *EnvelopeSignature `json:"signature,omitempty" yaml:"signature,omitempty"`
|
||||
Caring *CaringDecisionMetadata `json:"caring,omitempty" yaml:"caring,omitempty"`
|
||||
}
|
||||
|
||||
// EnvelopeSignatureMode is how the responder authenticates the envelope.
|
||||
type EnvelopeSignatureMode string
|
||||
|
||||
const (
|
||||
EnvelopeSignatureSigned EnvelopeSignatureMode = "signed"
|
||||
EnvelopeSignatureUnsigned EnvelopeSignatureMode = "unsigned"
|
||||
)
|
||||
|
||||
// EnvelopeSignature is a detached signature over the canonical envelope with
|
||||
// this field omitted (FLEX-WP-0024). It is not decision material and is not
|
||||
// part of request_digest.
|
||||
type EnvelopeSignature struct {
|
||||
Mode EnvelopeSignatureMode `json:"mode" yaml:"mode"`
|
||||
Alg string `json:"alg,omitempty" yaml:"alg,omitempty"`
|
||||
Kid string `json:"kid,omitempty" yaml:"kid,omitempty"`
|
||||
Value string `json:"value,omitempty" yaml:"value,omitempty"`
|
||||
}
|
||||
|
||||
func UnsignedEnvelopeSignature() *EnvelopeSignature {
|
||||
return &EnvelopeSignature{Mode: EnvelopeSignatureUnsigned}
|
||||
}
|
||||
|
||||
// DecisionLifetimeKind identifies how an allow ends.
|
||||
type DecisionLifetimeKind string
|
||||
|
||||
const (
|
||||
DecisionLifetimeTTL DecisionLifetimeKind = "ttl"
|
||||
)
|
||||
|
||||
// DefaultAllowTTL is the engine default when a policy package omits allow_ttl.
|
||||
const DefaultAllowTTL = 15 * time.Minute
|
||||
|
||||
// ReasonAllowLifetimeUnstated is the deny reason for an allow with no stated end.
|
||||
const ReasonAllowLifetimeUnstated = "allow_lifetime_unstated"
|
||||
|
||||
// DecisionLifetime bounds an allow (§9.7.1). flex-auth has no session concept,
|
||||
// so the first honest shape is a policy-package-declared TTL.
|
||||
type DecisionLifetime struct {
|
||||
Kind DecisionLifetimeKind `json:"kind" yaml:"kind"`
|
||||
TTL string `json:"ttl,omitempty" yaml:"ttl,omitempty"`
|
||||
NotBefore string `json:"not_before,omitempty" yaml:"not_before,omitempty"`
|
||||
ExpiresAt string `json:"expires_at" yaml:"expires_at"`
|
||||
}
|
||||
|
||||
// DecisionBinding is the exact normalized authorization request evaluated by
|
||||
// a decision. It lets a consumer verify structured action, target, actor, and
|
||||
// context fields without parsing reason or diagnostic prose.
|
||||
type DecisionBinding struct {
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Subject SubjectRef `json:"subject" yaml:"subject"`
|
||||
Action string `json:"action" yaml:"action"`
|
||||
Resource ResourceRef `json:"resource" yaml:"resource"`
|
||||
Context map[string]any `json:"context,omitempty" yaml:"context,omitempty"`
|
||||
// Purpose is "readback" on an advisory readback decision and absent on an
|
||||
// enforcement decision (FLEX-DEC-2026-019).
|
||||
Purpose string `json:"purpose,omitempty" yaml:"purpose,omitempty"`
|
||||
RequestDigest string `json:"request_digest" yaml:"request_digest"`
|
||||
|
||||
// ApprovalBindingDigest is RequestDigest computed with the approval claim
|
||||
// removed from context. It exists to break a circularity: an approval's
|
||||
// pdp_digest is recorded at issue time, but the request that later carries
|
||||
// the claim inside its hashed context has a different RequestDigest by
|
||||
// construction, so a claim can never name the request that carries it.
|
||||
//
|
||||
// This digest is stable across attaching the claim, so it is the value
|
||||
// claim.binding.pdp_digest must equal (GH-DEC-2026-008). It is NOT a replay
|
||||
// identity and must not be used as one: two requests differing only in
|
||||
// which approval was presented share it, and the decision does not.
|
||||
ApprovalBindingDigest string `json:"approval_binding_digest,omitempty" yaml:"approval_binding_digest,omitempty"`
|
||||
|
||||
// SubmittedRequestDigest is RequestDigest over the request exactly as the
|
||||
// consumer sent it, before the evaluator overlays registry facts onto the
|
||||
// subject and resource.
|
||||
//
|
||||
// It exists because RequestDigest is not consumer-computable and was
|
||||
// published as though it were. The evaluator hashes the ENRICHED request —
|
||||
// subject.tenant, subject.attributes, and resource attributes the registry
|
||||
// contributed — and the registry is flex-auth's, so a consumer recomputing
|
||||
// the digest over what it sent gets a different value on every real allow.
|
||||
// secrets-engine found this on its first live request (FLEX-DEC-2026-012).
|
||||
//
|
||||
// This is the digest a PEP compares for §6.4 obligation 2's replay test.
|
||||
// Nothing is lost by hashing the pre-enrichment form: enrichment is a
|
||||
// function of the request and the registry snapshot, and
|
||||
// provenance.registry_snapshot_digest already pins the snapshot, so
|
||||
// SubmittedRequestDigest together with that digest identifies the evaluated
|
||||
// request completely.
|
||||
SubmittedRequestDigest string `json:"submitted_request_digest,omitempty" yaml:"submitted_request_digest,omitempty"`
|
||||
}
|
||||
|
||||
// ApprovalContextKey is the context key carrying an approval-engine
|
||||
// approval-claim. It is excluded from ApprovalBindingDigest and from nothing
|
||||
// else.
|
||||
const ApprovalContextKey = "approval"
|
||||
|
||||
// requestDigestMaterial is the exact tuple hashed for §6.4.2 replay. Request
|
||||
// id, policy version, and caring_context are excluded: id is correlation, the
|
||||
// version is provenance, and caring_context is an input-claim digest.
|
||||
type requestDigestMaterial struct {
|
||||
Tenant string `json:"tenant,omitempty"`
|
||||
Subject SubjectRef `json:"subject"`
|
||||
Action string `json:"action"`
|
||||
Resource ResourceRef `json:"resource"`
|
||||
Context map[string]any `json:"context,omitempty"`
|
||||
Purpose string `json:"purpose,omitempty"`
|
||||
}
|
||||
|
||||
// NewDecisionBinding returns a stable structured binding for the exact request
|
||||
// an evaluator consumed.
|
||||
//
|
||||
// Prefer NewDecisionBindingFor, which also records the digest of the request as
|
||||
// submitted. This form leaves SubmittedRequestDigest empty, which reads as "the
|
||||
// evaluator did not record one" rather than "the two are equal".
|
||||
func NewDecisionBinding(request CheckRequest) *DecisionBinding {
|
||||
contextCopy := make(map[string]any, len(request.Context))
|
||||
for key, value := range request.Context {
|
||||
contextCopy[key] = value
|
||||
}
|
||||
binding := &DecisionBinding{
|
||||
Tenant: request.Tenant,
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: request.Resource,
|
||||
Context: contextCopy,
|
||||
Purpose: request.Purpose,
|
||||
RequestDigest: RequestDigest(request),
|
||||
}
|
||||
if _, carries := request.Context[ApprovalContextKey]; carries {
|
||||
binding.ApprovalBindingDigest = ApprovalBindingDigest(request)
|
||||
}
|
||||
return binding
|
||||
}
|
||||
|
||||
// NewDecisionBindingFor records the binding of the evaluated request together
|
||||
// with the digest of the request as submitted.
|
||||
//
|
||||
// The two arguments are the same request before and after the evaluator
|
||||
// overlaid registry facts. Where a request named nothing the registry knows they
|
||||
// are equal, and the field is emitted anyway: a consumer that only sees it on
|
||||
// enriched decisions would build a check that passes by absence.
|
||||
func NewDecisionBindingFor(evaluated, submitted CheckRequest) *DecisionBinding {
|
||||
binding := NewDecisionBinding(evaluated)
|
||||
binding.SubmittedRequestDigest = RequestDigest(submitted)
|
||||
return binding
|
||||
}
|
||||
|
||||
// ApprovalBindingDigest is RequestDigest over the same material with the
|
||||
// approval claim removed from context.
|
||||
//
|
||||
// When a request carries no approval claim the two are identical, which is the
|
||||
// point: an approval issued against a claim-free Check records that Check's
|
||||
// request_digest, and the later claim-bearing request reproduces the same value
|
||||
// here. Comparing it to claim.binding.pdp_digest establishes correspondence by
|
||||
// identity rather than by translating between two action vocabularies
|
||||
// (GH-DEC-2026-008).
|
||||
func ApprovalBindingDigest(request CheckRequest) string {
|
||||
if _, carries := request.Context[ApprovalContextKey]; !carries {
|
||||
return RequestDigest(request)
|
||||
}
|
||||
stripped := make(map[string]any, len(request.Context))
|
||||
for key, value := range request.Context {
|
||||
if key == ApprovalContextKey {
|
||||
continue
|
||||
}
|
||||
stripped[key] = value
|
||||
}
|
||||
if len(stripped) == 0 {
|
||||
stripped = nil
|
||||
}
|
||||
return CanonicalDigest(requestDigestMaterial{
|
||||
Tenant: request.Tenant,
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: request.Resource,
|
||||
Context: stripped,
|
||||
Purpose: request.Purpose,
|
||||
})
|
||||
}
|
||||
|
||||
// RequestDigest is the mechanical §6.4.2 replay test: SHA-256 over canonical
|
||||
// JSON of tenant, subject, action, resource, context, and purpose. Purpose is
|
||||
// omitted when empty, so enforcement digests are unchanged by its existence.
|
||||
func RequestDigest(request CheckRequest) string {
|
||||
return CanonicalDigest(requestDigestMaterial{
|
||||
Tenant: request.Tenant,
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: request.Resource,
|
||||
Context: request.Context,
|
||||
Purpose: request.Purpose,
|
||||
})
|
||||
}
|
||||
|
||||
// CanonicalDigest returns "sha256:" plus the hex SHA-256 of canonical JSON.
|
||||
// encoding/json sorts map keys, so two equal Go values agree.
|
||||
func CanonicalDigest(value any) string {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
sum := sha256.Sum256(nil)
|
||||
return "sha256:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
return "sha256:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// InputClaimDigests hashes the request-time claim classes the evaluator joined.
|
||||
func InputClaimDigests(request CheckRequest) map[string]string {
|
||||
digests := make(map[string]string)
|
||||
if len(request.Context) > 0 {
|
||||
digests["context"] = CanonicalDigest(request.Context)
|
||||
}
|
||||
if request.CaringContext != nil {
|
||||
digests["caring_context"] = CanonicalDigest(request.CaringContext)
|
||||
}
|
||||
if len(digests) == 0 {
|
||||
return nil
|
||||
}
|
||||
return digests
|
||||
}
|
||||
|
||||
// DecisionCompletion carries evaluator-side inputs used to finish an envelope.
|
||||
type DecisionCompletion struct {
|
||||
AllowTTL string
|
||||
Now time.Time
|
||||
}
|
||||
|
||||
// CompleteDecision stamps contract version, input-claim digests, decision time,
|
||||
// and an explicit allow lifetime. An allow with no stated end becomes a deny.
|
||||
func CompleteDecision(envelope *DecisionEnvelope, request CheckRequest, completion DecisionCompletion) {
|
||||
if envelope == nil {
|
||||
return
|
||||
}
|
||||
if envelope.ContractVersion == "" {
|
||||
envelope.ContractVersion = DecisionRecordContractV1
|
||||
}
|
||||
if envelope.Provenance.InputClaimDigests == nil {
|
||||
envelope.Provenance.InputClaimDigests = InputClaimDigests(request)
|
||||
}
|
||||
ApplyAllowLifetime(envelope, completion.AllowTTL, completion.Now)
|
||||
}
|
||||
|
||||
// ParseAllowTTL resolves a package-declared TTL. ok is false when the allow
|
||||
// would have no stated end. Invalid strings return an error so package
|
||||
// validation can reject them.
|
||||
func ParseAllowTTL(declared string) (time.Duration, error) {
|
||||
trimmed := strings.TrimSpace(declared)
|
||||
if trimmed == "" {
|
||||
return DefaultAllowTTL, nil
|
||||
}
|
||||
if strings.EqualFold(trimmed, "none") {
|
||||
return 0, nil
|
||||
}
|
||||
ttl, err := time.ParseDuration(trimmed)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("allow_ttl %q is not a Go duration: %w", declared, err)
|
||||
}
|
||||
if ttl <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return ttl, nil
|
||||
}
|
||||
|
||||
// ApplyAllowLifetime sets DecisionTime and, for allows, an explicit TTL. A
|
||||
// missing or zero TTL denies the allow rather than mint a standing grant.
|
||||
func ApplyAllowLifetime(envelope *DecisionEnvelope, declaredTTL string, now time.Time) {
|
||||
if envelope == nil {
|
||||
return
|
||||
}
|
||||
if now.IsZero() {
|
||||
now = time.Now().UTC()
|
||||
} else {
|
||||
now = now.UTC()
|
||||
}
|
||||
if envelope.Provenance.DecisionTime == "" {
|
||||
envelope.Provenance.DecisionTime = now.Format(time.RFC3339)
|
||||
}
|
||||
if envelope.Effect != DecisionEffectAllow {
|
||||
return
|
||||
}
|
||||
ttl, err := ParseAllowTTL(declaredTTL)
|
||||
if err != nil || ttl <= 0 {
|
||||
if envelope.Diagnostics == nil {
|
||||
envelope.Diagnostics = map[string]any{}
|
||||
}
|
||||
if envelope.Reason != "" {
|
||||
envelope.Diagnostics["unstated_allow_reason"] = envelope.Reason
|
||||
}
|
||||
envelope.Effect = DecisionEffectDeny
|
||||
envelope.Reason = ReasonAllowLifetimeUnstated
|
||||
envelope.MatchedRule = ReasonAllowLifetimeUnstated
|
||||
envelope.Lifetime = nil
|
||||
return
|
||||
}
|
||||
display := strings.TrimSpace(declaredTTL)
|
||||
if display == "" {
|
||||
display = "15m"
|
||||
}
|
||||
envelope.Lifetime = &DecisionLifetime{
|
||||
Kind: DecisionLifetimeTTL,
|
||||
TTL: display,
|
||||
NotBefore: now.Format(time.RFC3339),
|
||||
ExpiresAt: now.Add(ttl).Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
// ActionAuthorizationStatus is the lifecycle state of a durable authorization.
|
||||
type ActionAuthorizationStatus string
|
||||
|
||||
const (
|
||||
ActionAuthorizationPending ActionAuthorizationStatus = "pending"
|
||||
ActionAuthorizationApproved ActionAuthorizationStatus = "approved"
|
||||
ActionAuthorizationDenied ActionAuthorizationStatus = "denied"
|
||||
ActionAuthorizationSuperseded ActionAuthorizationStatus = "superseded"
|
||||
ActionAuthorizationExpired ActionAuthorizationStatus = "expired"
|
||||
ActionAuthorizationRevoked ActionAuthorizationStatus = "revoked"
|
||||
)
|
||||
|
||||
// ActionAuthorization joins a durable approval lifecycle to one exact
|
||||
// flex-auth request and decision. Storage and approval collection remain the
|
||||
// responsibility of the organizational decision authority.
|
||||
type ActionAuthorization struct {
|
||||
SchemaVersion string `json:"schema_version" yaml:"schema_version"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Status ActionAuthorizationStatus `json:"status" yaml:"status"`
|
||||
SupersededBy string `json:"superseded_by,omitempty" yaml:"superseded_by,omitempty"`
|
||||
Request CheckRequest `json:"request" yaml:"request"`
|
||||
Validity ActionAuthorizationValidity `json:"validity" yaml:"validity"`
|
||||
Approvals ActionAuthorizationApprovals `json:"approvals" yaml:"approvals"`
|
||||
Decision DecisionEnvelope `json:"decision" yaml:"decision"`
|
||||
Provenance map[string]any `json:"provenance,omitempty" yaml:"provenance,omitempty"`
|
||||
}
|
||||
|
||||
// ActionAuthorizationValidity bounds execution of an approved action.
|
||||
type ActionAuthorizationValidity struct {
|
||||
NotBefore string `json:"not_before,omitempty" yaml:"not_before,omitempty"`
|
||||
ExpiresAt string `json:"expires_at" yaml:"expires_at"`
|
||||
}
|
||||
|
||||
// ActionAuthorizationApprovals declares the approval threshold and evidence.
|
||||
type ActionAuthorizationApprovals struct {
|
||||
RequiredCount int `json:"required_count" yaml:"required_count"`
|
||||
Entries []ActionAuthorizationApprovalEntry `json:"entries" yaml:"entries"`
|
||||
}
|
||||
|
||||
// ActionAuthorizationApprovalEntry is one authenticated approver's evidence.
|
||||
type ActionAuthorizationApprovalEntry struct {
|
||||
SubjectID string `json:"subject_id" yaml:"subject_id"`
|
||||
ApprovedAt string `json:"approved_at" yaml:"approved_at"`
|
||||
Assurance string `json:"assurance,omitempty" yaml:"assurance,omitempty"`
|
||||
EvidenceRef string `json:"evidence_ref,omitempty" yaml:"evidence_ref,omitempty"`
|
||||
}
|
||||
|
||||
// Obligation describes a follow-up behavior required by a decision.
|
||||
type Obligation struct {
|
||||
Type string `json:"type" yaml:"type"`
|
||||
Parameters map[string]any `json:"parameters,omitempty" yaml:"parameters,omitempty"`
|
||||
}
|
||||
|
||||
// DecisionProvenance captures evaluator and policy provenance.
|
||||
type DecisionProvenance struct {
|
||||
Evaluator string `json:"evaluator" yaml:"evaluator"`
|
||||
Mode string `json:"mode" yaml:"mode"`
|
||||
PolicyPackage string `json:"policy_package,omitempty" yaml:"policy_package,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty" yaml:"policy_version,omitempty"`
|
||||
PolicyPackageDigest string `json:"policy_package_digest,omitempty" yaml:"policy_package_digest,omitempty"`
|
||||
RegistrySnapshotDigest string `json:"registry_snapshot_digest,omitempty" yaml:"registry_snapshot_digest,omitempty"`
|
||||
DirectoryETag string `json:"directory_etag,omitempty" yaml:"directory_etag,omitempty"`
|
||||
InputClaimDigests map[string]string `json:"input_claim_digests,omitempty" yaml:"input_claim_digests,omitempty"`
|
||||
DecisionTime string `json:"decision_time,omitempty" yaml:"decision_time,omitempty"`
|
||||
ApprovalObservation *ApprovalObservationProvenance `json:"approval_observation,omitempty" yaml:"approval_observation,omitempty"`
|
||||
Caller *CallerProvenance `json:"caller,omitempty" yaml:"caller,omitempty"`
|
||||
}
|
||||
|
||||
// ApprovalObservationProvenance binds fresh server-owned fact evidence without
|
||||
// rewriting the original carried claim/context or either PDP request digest.
|
||||
type ApprovalObservationProvenance struct {
|
||||
SourceID string `json:"source_id"`
|
||||
SourceRevision string `json:"source_revision"`
|
||||
ConfigurationDigest string `json:"configuration_digest"`
|
||||
ClaimDigest string `json:"claim_digest"`
|
||||
NativeBindingDigest string `json:"native_binding_digest"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
NotAfter string `json:"not_after"`
|
||||
ValidatedAt string `json:"validated_at"`
|
||||
}
|
||||
|
||||
// CallerProvenance records how the request was authenticated to flex-auth.
|
||||
// It is not decision material: the same request from a different authenticated
|
||||
// caller must decide identically. Mode is required. Under disabled the object
|
||||
// is {"mode":"disabled"} with no principal (FLEX-DEC-2026-009).
|
||||
type CallerProvenance struct {
|
||||
Mode string `json:"mode" yaml:"mode"`
|
||||
Principal string `json:"principal,omitempty" yaml:"principal,omitempty"`
|
||||
Audience string `json:"audience,omitempty" yaml:"audience,omitempty"`
|
||||
NotAfter string `json:"not_after,omitempty" yaml:"not_after,omitempty"`
|
||||
}
|
||||
|
||||
// CaringDecisionMetadata carries CARING descriptor and conformance details in
|
||||
// a decision envelope.
|
||||
type CaringDecisionMetadata struct {
|
||||
Profile string `json:"profile" yaml:"profile"`
|
||||
Descriptor *CaringAccessDescriptor `json:"descriptor,omitempty" yaml:"descriptor,omitempty"`
|
||||
RestrictionsEvaluated []Restriction `json:"restrictions_evaluated,omitempty" yaml:"restrictions_evaluated,omitempty"`
|
||||
ExposureModes []ExposureMode `json:"exposure_modes,omitempty" yaml:"exposure_modes,omitempty"`
|
||||
DerivedCapabilities []CaringDerivedCapability `json:"derived_capabilities,omitempty" yaml:"derived_capabilities,omitempty"`
|
||||
ConformanceFindings []CaringConformanceFinding `json:"conformance_findings,omitempty" yaml:"conformance_findings,omitempty"`
|
||||
ExposureEvent *CaringExposureEvent `json:"exposure_event,omitempty" yaml:"exposure_event,omitempty"`
|
||||
}
|
||||
|
||||
// AuditEvent is the local log shape for decisions and exposure events.
|
||||
type AuditEvent struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Type string `json:"type" yaml:"type"`
|
||||
DecisionID string `json:"decision_id,omitempty" yaml:"decision_id,omitempty"`
|
||||
Subject SubjectRef `json:"subject" yaml:"subject"`
|
||||
Resource ResourceRef `json:"resource,omitempty" yaml:"resource,omitempty"`
|
||||
Action string `json:"action,omitempty" yaml:"action,omitempty"`
|
||||
Effect DecisionEffect `json:"effect,omitempty" yaml:"effect,omitempty"`
|
||||
Timestamp string `json:"timestamp,omitempty" yaml:"timestamp,omitempty"`
|
||||
ExposureEvent *CaringExposureEvent `json:"exposure_event,omitempty" yaml:"exposure_event,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,335 @@
|
|||
package api
|
||||
|
||||
// CaringProfileCaring040RC2 is the executable profile identifier for the
|
||||
// CARING 0.4.0-RC2 standard pinned by flex-auth.
|
||||
const CaringProfileCaring040RC2 = "caring-0.4.0-rc2"
|
||||
|
||||
// SubjectType is the CARING subject dimension.
|
||||
type SubjectType string
|
||||
|
||||
const (
|
||||
SubjectTypeHuman SubjectType = "Human"
|
||||
SubjectTypeGroup SubjectType = "Group"
|
||||
SubjectTypeOrganization SubjectType = "Organization"
|
||||
SubjectTypeService SubjectType = "Service"
|
||||
SubjectTypeAutomation SubjectType = "Automation"
|
||||
SubjectTypeAgent SubjectType = "Agent"
|
||||
SubjectTypeSystem SubjectType = "System"
|
||||
SubjectTypeDevice SubjectType = "Device"
|
||||
SubjectTypeProcess SubjectType = "Process"
|
||||
SubjectTypeAnonymous SubjectType = "Anonymous"
|
||||
SubjectTypeUnknown SubjectType = "Unknown"
|
||||
)
|
||||
|
||||
// OrganizationRelation is the CARING organization-relation dimension.
|
||||
type OrganizationRelation string
|
||||
|
||||
const (
|
||||
OrganizationRelationVendor OrganizationRelation = "Vendor"
|
||||
OrganizationRelationServiceProvider OrganizationRelation = "ServiceProvider"
|
||||
OrganizationRelationDistributor OrganizationRelation = "Distributor"
|
||||
OrganizationRelationConsultant OrganizationRelation = "Consultant"
|
||||
OrganizationRelationCustomer OrganizationRelation = "Customer"
|
||||
OrganizationRelationCommunity OrganizationRelation = "Community"
|
||||
OrganizationRelationAuthority OrganizationRelation = "Authority"
|
||||
OrganizationRelationUnknown OrganizationRelation = "Unknown"
|
||||
)
|
||||
|
||||
// CanonicalRole is the CARING lifecycle responsibility posture.
|
||||
type CanonicalRole string
|
||||
|
||||
const (
|
||||
CanonicalRoleCreator CanonicalRole = "Creator"
|
||||
CanonicalRoleBuilder CanonicalRole = "Builder"
|
||||
CanonicalRoleVerifier CanonicalRole = "Verifier"
|
||||
CanonicalRoleMaintainer CanonicalRole = "Maintainer"
|
||||
CanonicalRoleIntegrator CanonicalRole = "Integrator"
|
||||
CanonicalRoleOperator CanonicalRole = "Operator"
|
||||
CanonicalRoleManager CanonicalRole = "Manager"
|
||||
CanonicalRoleCoach CanonicalRole = "Coach"
|
||||
CanonicalRoleDoer CanonicalRole = "Doer"
|
||||
)
|
||||
|
||||
// ScopeLevel is the CARING scope ladder.
|
||||
type ScopeLevel string
|
||||
|
||||
const (
|
||||
ScopeLevelEcosystem ScopeLevel = "Ecosystem"
|
||||
ScopeLevelProduct ScopeLevel = "Product"
|
||||
ScopeLevelPlatform ScopeLevel = "Platform"
|
||||
ScopeLevelCluster ScopeLevel = "Cluster"
|
||||
ScopeLevelEnvironment ScopeLevel = "Environment"
|
||||
ScopeLevelTenant ScopeLevel = "Tenant"
|
||||
ScopeLevelNamespace ScopeLevel = "Namespace"
|
||||
ScopeLevelDomain ScopeLevel = "Domain"
|
||||
ScopeLevelWorkspace ScopeLevel = "Workspace"
|
||||
ScopeLevelProject ScopeLevel = "Project"
|
||||
ScopeLevelProcess ScopeLevel = "Process"
|
||||
ScopeLevelDataset ScopeLevel = "Dataset"
|
||||
ScopeLevelResource ScopeLevel = "Resource"
|
||||
ScopeLevelSubresource ScopeLevel = "Subresource"
|
||||
ScopeLevelRecord ScopeLevel = "Record"
|
||||
ScopeLevelField ScopeLevel = "Field"
|
||||
ScopeLevelAction ScopeLevel = "Action"
|
||||
)
|
||||
|
||||
// Plane is the CARING access-surface dimension.
|
||||
type Plane string
|
||||
|
||||
const (
|
||||
PlaneIntent Plane = "Intent"
|
||||
PlaneBuild Plane = "Build"
|
||||
PlaneRuntime Plane = "Runtime"
|
||||
PlaneExecution Plane = "Execution"
|
||||
PlaneConfiguration Plane = "Configuration"
|
||||
PlaneData Plane = "Data"
|
||||
PlaneIdentity Plane = "Identity"
|
||||
PlanePolicy Plane = "Policy"
|
||||
PlaneSecret Plane = "Secret"
|
||||
PlaneAudit Plane = "Audit"
|
||||
PlaneCommercial Plane = "Commercial"
|
||||
PlaneCommunity Plane = "Community"
|
||||
)
|
||||
|
||||
// Capability is a CARING capability verb.
|
||||
type Capability string
|
||||
|
||||
const (
|
||||
CapabilityView Capability = "View"
|
||||
CapabilityViewCollection Capability = "ViewCollection"
|
||||
CapabilityObserve Capability = "Observe"
|
||||
CapabilityCreate Capability = "Create"
|
||||
CapabilityEditOwn Capability = "EditOwn"
|
||||
CapabilityEditAssigned Capability = "EditAssigned"
|
||||
CapabilityEditAny Capability = "EditAny"
|
||||
CapabilityDeleteOwn Capability = "DeleteOwn"
|
||||
CapabilityDeleteAny Capability = "DeleteAny"
|
||||
CapabilityBulkDelete Capability = "BulkDelete"
|
||||
CapabilitySubmit Capability = "Submit"
|
||||
CapabilityComment Capability = "Comment"
|
||||
CapabilityReview Capability = "Review"
|
||||
CapabilityApprove Capability = "Approve"
|
||||
CapabilityReject Capability = "Reject"
|
||||
CapabilityPublish Capability = "Publish"
|
||||
CapabilityArchive Capability = "Archive"
|
||||
CapabilityRestore Capability = "Restore"
|
||||
CapabilityExecute Capability = "Execute"
|
||||
CapabilityConfigure Capability = "Configure"
|
||||
CapabilityOperate Capability = "Operate"
|
||||
CapabilityDeploy Capability = "Deploy"
|
||||
CapabilityIntegrate Capability = "Integrate"
|
||||
CapabilityGrant Capability = "Grant"
|
||||
CapabilityRevoke Capability = "Revoke"
|
||||
CapabilityDelegate Capability = "Delegate"
|
||||
CapabilityImpersonate Capability = "Impersonate"
|
||||
CapabilityExport Capability = "Export"
|
||||
CapabilityImport Capability = "Import"
|
||||
CapabilityReplicate Capability = "Replicate"
|
||||
CapabilityEncrypt Capability = "Encrypt"
|
||||
CapabilityDecrypt Capability = "Decrypt"
|
||||
CapabilityMask Capability = "Mask"
|
||||
CapabilityInspect Capability = "Inspect"
|
||||
CapabilityAudit Capability = "Audit"
|
||||
CapabilityOverride Capability = "Override"
|
||||
CapabilityEscalate Capability = "Escalate"
|
||||
CapabilityBind Capability = "Bind"
|
||||
CapabilityUse Capability = "Use"
|
||||
)
|
||||
|
||||
// ExposureMode describes how much information becomes visible or extractable.
|
||||
type ExposureMode string
|
||||
|
||||
const (
|
||||
ExposureModeNone ExposureMode = "None"
|
||||
ExposureModeMetadata ExposureMode = "Metadata"
|
||||
ExposureModeMasked ExposureMode = "Masked"
|
||||
ExposureModeAggregated ExposureMode = "Aggregated"
|
||||
ExposureModeSynthetic ExposureMode = "Synthetic"
|
||||
ExposureModePseudonymous ExposureMode = "Pseudonymous"
|
||||
ExposureModeEncrypted ExposureMode = "Encrypted"
|
||||
ExposureModePlaintext ExposureMode = "Plaintext"
|
||||
ExposureModeSecretMaterial ExposureMode = "SecretMaterial"
|
||||
ExposureModeExportable ExposureMode = "Exportable"
|
||||
ExposureModeCrossTenantAggregate ExposureMode = "CrossTenantAggregate"
|
||||
)
|
||||
|
||||
// Condition is a CARING runtime or governance condition.
|
||||
type Condition string
|
||||
|
||||
const (
|
||||
ConditionMFARequired Condition = "MFARequired"
|
||||
ConditionDeviceTrusted Condition = "DeviceTrusted"
|
||||
ConditionNetworkTrusted Condition = "NetworkTrusted"
|
||||
ConditionTicketRequired Condition = "TicketRequired"
|
||||
ConditionTenantConsentRequired Condition = "TenantConsentRequired"
|
||||
ConditionCustomerApprovalRequired Condition = "CustomerApprovalRequired"
|
||||
ConditionDualApprovalRequired Condition = "DualApprovalRequired"
|
||||
ConditionTimeLimited Condition = "TimeLimited"
|
||||
ConditionBusinessHoursOnly Condition = "BusinessHoursOnly"
|
||||
ConditionEmergencyOnly Condition = "EmergencyOnly"
|
||||
ConditionTrainingRequired Condition = "TrainingRequired"
|
||||
ConditionContractRequired Condition = "ContractRequired"
|
||||
ConditionNDARequired Condition = "NDARequired"
|
||||
ConditionPurposeBound Condition = "PurposeBound"
|
||||
ConditionCaseBound Condition = "CaseBound"
|
||||
ConditionEnvironmentBound Condition = "EnvironmentBound"
|
||||
ConditionNamespaceBound Condition = "NamespaceBound"
|
||||
ConditionPipelineBound Condition = "PipelineBound"
|
||||
ConditionChangeWindowBound Condition = "ChangeWindowBound"
|
||||
ConditionLogged Condition = "Logged"
|
||||
ConditionRecorded Condition = "Recorded"
|
||||
ConditionNotificationRequired Condition = "NotificationRequired"
|
||||
ConditionPostReviewRequired Condition = "PostReviewRequired"
|
||||
ConditionHumanReviewRequired Condition = "HumanReviewRequired"
|
||||
ConditionPolicyReviewRequired Condition = "PolicyReviewRequired"
|
||||
ConditionWorkloadIdentityRequired Condition = "WorkloadIdentityRequired"
|
||||
)
|
||||
|
||||
// LifecycleState describes why access exists now.
|
||||
type LifecycleState string
|
||||
|
||||
const (
|
||||
LifecycleStateDesign LifecycleState = "Design"
|
||||
LifecycleStateBuild LifecycleState = "Build"
|
||||
LifecycleStateTest LifecycleState = "Test"
|
||||
LifecycleStateReview LifecycleState = "Review"
|
||||
LifecycleStateRelease LifecycleState = "Release"
|
||||
LifecycleStateOnboard LifecycleState = "Onboard"
|
||||
LifecycleStateIntegrate LifecycleState = "Integrate"
|
||||
LifecycleStateMigrate LifecycleState = "Migrate"
|
||||
LifecycleStateOperate LifecycleState = "Operate"
|
||||
LifecycleStateSupport LifecycleState = "Support"
|
||||
LifecycleStateImprove LifecycleState = "Improve"
|
||||
LifecycleStateDeprecate LifecycleState = "Deprecate"
|
||||
LifecycleStateArchive LifecycleState = "Archive"
|
||||
LifecycleStateIncident LifecycleState = "Incident"
|
||||
LifecycleStateLegal LifecycleState = "Legal"
|
||||
LifecycleStateTerminate LifecycleState = "Terminate"
|
||||
)
|
||||
|
||||
// Restriction is an overriding CARING deny or limiting policy effect.
|
||||
type Restriction string
|
||||
|
||||
const (
|
||||
RestrictionNoAccess Restriction = "NoAccess"
|
||||
RestrictionSuspended Restriction = "Suspended"
|
||||
RestrictionTerminated Restriction = "Terminated"
|
||||
RestrictionQuarantined Restriction = "Quarantined"
|
||||
RestrictionScopeExcluded Restriction = "ScopeExcluded"
|
||||
RestrictionDataClassRestricted Restriction = "DataClassRestricted"
|
||||
RestrictionLegalHold Restriction = "LegalHold"
|
||||
RestrictionExportBlocked Restriction = "ExportBlocked"
|
||||
RestrictionImpersonationBlocked Restriction = "ImpersonationBlocked"
|
||||
RestrictionCrossTenantBlocked Restriction = "CrossTenantBlocked"
|
||||
RestrictionSecretAccessBlocked Restriction = "SecretAccessBlocked"
|
||||
RestrictionPolicyFrozen Restriction = "PolicyFrozen"
|
||||
RestrictionEmergencyLocked Restriction = "EmergencyLocked"
|
||||
RestrictionRiskDenied Restriction = "RiskDenied"
|
||||
RestrictionExecutionBlocked Restriction = "ExecutionBlocked"
|
||||
RestrictionWorkloadCreationBlocked Restriction = "WorkloadCreationBlocked"
|
||||
RestrictionPrivilegeEscalationBlocked Restriction = "PrivilegeEscalationBlocked"
|
||||
)
|
||||
|
||||
// ExposureEventType is a CARING exceptional or irregular access class.
|
||||
type ExposureEventType string
|
||||
|
||||
const (
|
||||
ExposureEventSupport ExposureEventType = "X-Support"
|
||||
ExposureEventBreakGlass ExposureEventType = "X-BreakGlass"
|
||||
ExposureEventSecurityTest ExposureEventType = "X-SecurityTest"
|
||||
ExposureEventIncident ExposureEventType = "X-Incident"
|
||||
ExposureEventLegalDemand ExposureEventType = "X-LegalDemand"
|
||||
ExposureEventComplianceAudit ExposureEventType = "X-ComplianceAudit"
|
||||
ExposureEventMigration ExposureEventType = "X-Migration"
|
||||
ExposureEventRecovery ExposureEventType = "X-Recovery"
|
||||
ExposureEventAdversarial ExposureEventType = "X-Adversarial"
|
||||
ExposureEventMisconfiguration ExposureEventType = "X-Misconfiguration"
|
||||
ExposureEventInducedAccess ExposureEventType = "X-InducedAccess"
|
||||
ExposureEventPrivilegeEscalation ExposureEventType = "X-PrivilegeEscalation"
|
||||
)
|
||||
|
||||
// AccessPath describes how access is exercised.
|
||||
type AccessPath string
|
||||
|
||||
const (
|
||||
AccessPathDirect AccessPath = "direct"
|
||||
AccessPathDelegated AccessPath = "delegated"
|
||||
AccessPathMediated AccessPath = "mediated"
|
||||
AccessPathInduced AccessPath = "induced"
|
||||
)
|
||||
|
||||
// CaringScope identifies where a CARING descriptor applies.
|
||||
type CaringScope struct {
|
||||
Level ScopeLevel `json:"level" yaml:"level"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Parent string `json:"parent,omitempty" yaml:"parent,omitempty"`
|
||||
Tenant string `json:"tenant,omitempty" yaml:"tenant,omitempty"`
|
||||
Resource string `json:"resource,omitempty" yaml:"resource,omitempty"`
|
||||
Attributes map[string]any `json:"attributes,omitempty" yaml:"attributes,omitempty"`
|
||||
}
|
||||
|
||||
// CaringAccessDescriptor is the executable flex-auth representation of a
|
||||
// CARING access assignment.
|
||||
type CaringAccessDescriptor struct {
|
||||
ID string `json:"id,omitempty" yaml:"id,omitempty"`
|
||||
Profile string `json:"profile" yaml:"profile"`
|
||||
SubjectType SubjectType `json:"subject_type" yaml:"subject_type"`
|
||||
OrganizationRelation OrganizationRelation `json:"organization_relation" yaml:"organization_relation"`
|
||||
CanonicalRole CanonicalRole `json:"canonical_role" yaml:"canonical_role"`
|
||||
Scope CaringScope `json:"scope" yaml:"scope"`
|
||||
Planes []Plane `json:"planes" yaml:"planes"`
|
||||
Capabilities []Capability `json:"capabilities" yaml:"capabilities"`
|
||||
ExposureModes []ExposureMode `json:"exposure_modes,omitempty" yaml:"exposure_modes,omitempty"`
|
||||
Conditions []Condition `json:"conditions,omitempty" yaml:"conditions,omitempty"`
|
||||
LifecycleState LifecycleState `json:"lifecycle_state,omitempty" yaml:"lifecycle_state,omitempty"`
|
||||
Restrictions []Restriction `json:"restrictions,omitempty" yaml:"restrictions,omitempty"`
|
||||
ExposureEvent ExposureEventType `json:"exposure_event,omitempty" yaml:"exposure_event,omitempty"`
|
||||
DerivedCapabilities []CaringDerivedCapability `json:"derived_capabilities,omitempty" yaml:"derived_capabilities,omitempty"`
|
||||
AccessPath AccessPath `json:"access_path,omitempty" yaml:"access_path,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// CaringDerivedCapability records effective authority created by another grant.
|
||||
type CaringDerivedCapability struct {
|
||||
Capability Capability `json:"capability" yaml:"capability"`
|
||||
Reason string `json:"reason" yaml:"reason"`
|
||||
Source string `json:"source,omitempty" yaml:"source,omitempty"`
|
||||
Planes []Plane `json:"planes,omitempty" yaml:"planes,omitempty"`
|
||||
ExposureModes []ExposureMode `json:"exposure_modes,omitempty" yaml:"exposure_modes,omitempty"`
|
||||
}
|
||||
|
||||
// CaringConformanceFinding is a diagnostic emitted by descriptive or
|
||||
// prescriptive CARING validation.
|
||||
type CaringConformanceFinding struct {
|
||||
Code string `json:"code" yaml:"code"`
|
||||
Severity string `json:"severity" yaml:"severity"`
|
||||
Message string `json:"message" yaml:"message"`
|
||||
Fields []string `json:"fields,omitempty" yaml:"fields,omitempty"`
|
||||
Descriptor string `json:"descriptor,omitempty" yaml:"descriptor,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// CaringExposureEvent records exceptional or irregular information exposure.
|
||||
type CaringExposureEvent struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Type ExposureEventType `json:"type" yaml:"type"`
|
||||
Actor string `json:"actor" yaml:"actor"`
|
||||
Subject string `json:"subject" yaml:"subject"`
|
||||
Descriptor *CaringAccessDescriptor `json:"descriptor,omitempty" yaml:"descriptor,omitempty"`
|
||||
Scope *CaringScope `json:"scope,omitempty" yaml:"scope,omitempty"`
|
||||
Planes []Plane `json:"planes,omitempty" yaml:"planes,omitempty"`
|
||||
CapabilitiesUsed []Capability `json:"capabilities_used,omitempty" yaml:"capabilities_used,omitempty"`
|
||||
DerivedCapabilities []CaringDerivedCapability `json:"derived_capabilities,omitempty" yaml:"derived_capabilities,omitempty"`
|
||||
ExposureModes []ExposureMode `json:"exposure_modes,omitempty" yaml:"exposure_modes,omitempty"`
|
||||
Reason string `json:"reason" yaml:"reason"`
|
||||
AuthoritySource string `json:"authority_source,omitempty" yaml:"authority_source,omitempty"`
|
||||
Approval string `json:"approval,omitempty" yaml:"approval,omitempty"`
|
||||
StartTime string `json:"start_time,omitempty" yaml:"start_time,omitempty"`
|
||||
EndTime string `json:"end_time,omitempty" yaml:"end_time,omitempty"`
|
||||
ResourcesAccessed []string `json:"resources_accessed,omitempty" yaml:"resources_accessed,omitempty"`
|
||||
Evidence []string `json:"evidence,omitempty" yaml:"evidence,omitempty"`
|
||||
NotificationStatus string `json:"notification_status,omitempty" yaml:"notification_status,omitempty"`
|
||||
PostReview string `json:"post_review,omitempty" yaml:"post_review,omitempty"`
|
||||
ConformanceFindings []CaringConformanceFinding `json:"conformance_findings,omitempty" yaml:"conformance_findings,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package api
|
||||
|
||||
// ResourceManifest is the shape a protected system publishes to register
|
||||
// its resources with flex-auth. The shape is pinned against the
|
||||
// Markitect-side emitter in markitect-tool (MKTT-WP-0014); see
|
||||
// schemas/resource_manifest.schema.json for the JSON Schema and
|
||||
// examples/markitect/resource_manifest.yaml for the canonical example.
|
||||
type ResourceManifest struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
System string `json:"system" yaml:"system"`
|
||||
Resources []Resource `json:"resources" yaml:"resources"`
|
||||
Actions []string `json:"actions,omitempty" yaml:"actions,omitempty"`
|
||||
CaringProfile string `json:"caring_profile,omitempty" yaml:"caring_profile,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Resource is one entry in a ResourceManifest.
|
||||
type Resource struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Type string `json:"type" yaml:"type"`
|
||||
Path string `json:"path,omitempty" yaml:"path,omitempty"`
|
||||
Parent string `json:"parent,omitempty" yaml:"parent,omitempty"`
|
||||
Labels []string `json:"labels,omitempty" yaml:"labels,omitempty"`
|
||||
TrustZone string `json:"trust_zone,omitempty" yaml:"trust_zone,omitempty"`
|
||||
Owner string `json:"owner,omitempty" yaml:"owner,omitempty"`
|
||||
Caring *CaringAccessDescriptor `json:"caring,omitempty" yaml:"caring,omitempty"`
|
||||
Attributes map[string]any `json:"attributes,omitempty" yaml:"attributes,omitempty"`
|
||||
}
|
||||
|
||||
// FlexAuthContractV0 is the metadata.flex_auth_contract value that
|
||||
// signals the v0 resource-registration contract.
|
||||
const FlexAuthContractV0 = "resource-registration-v0"
|
||||
|
|
@ -0,0 +1,296 @@
|
|||
// Package decisionpep authenticates the producer's decision record for one
|
||||
// current request. It never evaluates policy, caches a verdict, or discovers trust.
|
||||
package decisionpep
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
var ErrRefused = errors.New("authenticated decision refused")
|
||||
|
||||
const nonceKey = "decisionpep_request_nonce"
|
||||
|
||||
const JSONProfile = "lossless-json-v1"
|
||||
const provenanceMode = "standalone/lossless-json-v1"
|
||||
const maxBytes = 2 << 20
|
||||
|
||||
// Admission is public, independently admitted owner configuration. TokenFile is
|
||||
// only a path to a private rotating caller credential, never a literal token.
|
||||
type Admission struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
CAFile string `json:"ca_file"`
|
||||
TokenFile string `json:"token_file"`
|
||||
Keys map[string]string `json:"keys"`
|
||||
Evaluator string `json:"evaluator"`
|
||||
PolicyPackage string `json:"policy_package"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
PolicyDigest string `json:"policy_digest"`
|
||||
RegistryDigest string `json:"registry_digest"`
|
||||
CallerPrincipal string `json:"caller_principal"`
|
||||
CallerAudience string `json:"caller_audience"`
|
||||
MaxTTL string `json:"max_ttl"`
|
||||
MaxClockSkew string `json:"max_clock_skew"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
admission Admission
|
||||
keys map[string]ed25519.PublicKey
|
||||
http *http.Client
|
||||
maxTTL, skew time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// Load reads a current independently admitted file. No trust is bootstrapped
|
||||
// from a PDP response, token contents, discovery endpoint, or environment value.
|
||||
func Load(path string) (*Client, error) {
|
||||
raw, err := readFile(path, false)
|
||||
if err != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
var a Admission
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&a) != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if _, err = d.Token(); err != io.EOF {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
return New(a)
|
||||
}
|
||||
|
||||
func New(a Admission) (*Client, error) {
|
||||
u, err := url.Parse(a.Endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "/v1/check" || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if !filepath.IsAbs(a.CAFile) || !filepath.IsAbs(a.TokenFile) || a.Evaluator == "" || a.PolicyPackage == "" || a.PolicyVersion == "" || a.CallerPrincipal == "" || a.CallerAudience == "" {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if !validDigest(a.PolicyDigest) || !validDigest(a.RegistryDigest) || len(a.Keys) == 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
ttl, err := time.ParseDuration(a.MaxTTL)
|
||||
if err != nil || ttl <= 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
skew, err := time.ParseDuration(a.MaxClockSkew)
|
||||
if err != nil || skew < 0 || skew > ttl {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
ca, err := readFile(a.CAFile, false)
|
||||
if err != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
keys := map[string]ed25519.PublicKey{}
|
||||
for kid, value := range a.Keys {
|
||||
b, e := base64.RawURLEncoding.Strict().DecodeString(value)
|
||||
if e != nil || kid == "" || len(b) != ed25519.PublicKeySize {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
keys[kid] = append(ed25519.PublicKey(nil), b...)
|
||||
}
|
||||
transport := &http.Transport{Proxy: nil, TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}, DisableKeepAlives: true}
|
||||
client := &http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return ErrRefused }}
|
||||
return &Client{admission: a, keys: keys, http: client, maxTTL: ttl, skew: skew, now: time.Now}, nil
|
||||
}
|
||||
|
||||
func validDigest(value string) bool {
|
||||
if !strings.HasPrefix(value, "sha256:") || len(value) != 71 {
|
||||
return false
|
||||
}
|
||||
_, e := hex.DecodeString(value[7:])
|
||||
return e == nil && strings.ToLower(value) == value
|
||||
}
|
||||
|
||||
func readFile(path string, private bool) ([]byte, error) {
|
||||
if !filepath.IsAbs(path) {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
f, e := os.Open(path)
|
||||
if e != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
defer f.Close()
|
||||
info, e := f.Stat()
|
||||
if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0022 != 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if private && info.Mode().Perm()&0007 != 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
b, e := io.ReadAll(io.LimitReader(f, maxBytes+1))
|
||||
if e != nil || len(b) > maxBytes {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Check sends exactly one request with a cryptographically fresh nonce. The
|
||||
// returned envelope is the producer's authenticated typed interpretation.
|
||||
// Callers must execute only the request's exact operation and honor their own
|
||||
// execution boundary; a login decision is never a later resource decision.
|
||||
func (c *Client) Check(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
refuse := func() (api.DecisionEnvelope, error) { return api.DecisionEnvelope{}, ErrRefused }
|
||||
if c == nil || request.Purpose != "" || request.Tenant == "" || request.Subject.ID == "" || request.Subject.Type == "" || request.Resource.ID == "" || request.Resource.Type == "" || request.Resource.System == "" || request.Action == "" {
|
||||
return refuse()
|
||||
}
|
||||
if request.Subject.Tenant != request.Tenant || request.Resource.Tenant != request.Tenant {
|
||||
return refuse()
|
||||
}
|
||||
if request.PolicyVersion != "" && request.PolicyVersion != c.admission.PolicyVersion {
|
||||
return refuse()
|
||||
}
|
||||
// Use the producer's typed representation and preserve numeric lexemes. A
|
||||
// producer that rounds before hashing fails this join rather than weakening it.
|
||||
raw, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&request) != nil {
|
||||
return refuse()
|
||||
}
|
||||
if request.Context == nil {
|
||||
request.Context = map[string]any{}
|
||||
}
|
||||
if _, exists := request.Context[nonceKey]; exists {
|
||||
return refuse()
|
||||
}
|
||||
nonce := make([]byte, 32)
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
return refuse()
|
||||
}
|
||||
request.Context[nonceKey] = hex.EncodeToString(nonce)
|
||||
request.Context["decisionpep_json_profile"] = JSONProfile
|
||||
request.ID = hex.EncodeToString(nonce)
|
||||
request.PolicyVersion = c.admission.PolicyVersion
|
||||
raw, err = json.Marshal(request)
|
||||
if err != nil || len(raw) > maxBytes {
|
||||
return refuse()
|
||||
}
|
||||
token, err := readFile(c.admission.TokenFile, true)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
value := strings.TrimSpace(string(token))
|
||||
if value == "" || strings.ContainsAny(value, " \t\r\n") {
|
||||
return refuse()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.admission.Endpoint, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Access-Engine-JSON-Profile", JSONProfile)
|
||||
req.Header.Set("Authorization", "Bearer "+value)
|
||||
started := c.now().UTC()
|
||||
response, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return refuse()
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxBytes+1))
|
||||
if err != nil || len(body) > maxBytes {
|
||||
return refuse()
|
||||
}
|
||||
envelope, err := sign.DecodeEnvelope(body)
|
||||
if err != nil || sign.Verify(envelope, c.keys) != nil {
|
||||
return refuse()
|
||||
}
|
||||
if c.validate(envelope, request, started, c.now().UTC()) != nil {
|
||||
return refuse()
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
func (c *Client) validate(e api.DecisionEnvelope, r api.CheckRequest, started, now time.Time) error {
|
||||
p := e.Provenance
|
||||
b := e.Binding
|
||||
l := e.Lifetime
|
||||
if e.ID == "" || e.ContractVersion != api.DecisionRecordContractV1 || e.Effect != api.DecisionEffectAllow || e.RequestID != r.ID || len(e.Obligations) != 0 || b == nil || l == nil {
|
||||
return ErrRefused
|
||||
}
|
||||
if p.Evaluator != c.admission.Evaluator || p.Mode != provenanceMode || p.PolicyPackage != c.admission.PolicyPackage || p.PolicyVersion != c.admission.PolicyVersion || p.PolicyPackageDigest != c.admission.PolicyDigest || p.RegistrySnapshotDigest != c.admission.RegistryDigest || e.MatchedPolicyVersion != p.PolicyVersion {
|
||||
return ErrRefused
|
||||
}
|
||||
if b.Purpose != "" || b.SubmittedRequestDigest != api.RequestDigest(r) || b.Tenant != r.Tenant || b.Action != r.Action || api.CanonicalDigest(b.Context) != api.CanonicalDigest(r.Context) {
|
||||
return ErrRefused
|
||||
}
|
||||
if !sameSubject(b.Subject, r.Subject) || !sameResource(b.Resource, r.Resource) || !sameSubject(e.Subject, b.Subject) || !sameResource(e.Resource, b.Resource) {
|
||||
return ErrRefused
|
||||
}
|
||||
evaluated := api.CheckRequest{Tenant: b.Tenant, Subject: b.Subject, Action: b.Action, Resource: b.Resource, Context: b.Context, Purpose: b.Purpose}
|
||||
if b.RequestDigest != api.RequestDigest(evaluated) {
|
||||
return ErrRefused
|
||||
}
|
||||
for k, v := range api.InputClaimDigests(r) {
|
||||
if p.InputClaimDigests[k] != v {
|
||||
return ErrRefused
|
||||
}
|
||||
}
|
||||
caller := p.Caller
|
||||
if caller == nil || caller.Mode != "enforce" || caller.Principal != c.admission.CallerPrincipal || caller.Audience != c.admission.CallerAudience {
|
||||
return ErrRefused
|
||||
}
|
||||
callerEnd, err := time.Parse(time.RFC3339Nano, caller.NotAfter)
|
||||
if err != nil || !now.Before(callerEnd) {
|
||||
return ErrRefused
|
||||
}
|
||||
decision, err := time.Parse(time.RFC3339Nano, p.DecisionTime)
|
||||
if err != nil || decision.Before(started.Add(-c.skew)) || decision.After(now.Add(c.skew)) {
|
||||
return ErrRefused
|
||||
}
|
||||
begin, err := time.Parse(time.RFC3339Nano, l.NotBefore)
|
||||
if err != nil || begin.After(now) {
|
||||
return ErrRefused
|
||||
}
|
||||
end, err := time.Parse(time.RFC3339Nano, l.ExpiresAt)
|
||||
if err != nil || !now.Before(end) || !end.After(begin) || end.Sub(begin) > c.maxTTL || end.After(callerEnd) {
|
||||
return ErrRefused
|
||||
}
|
||||
ttl, err := time.ParseDuration(l.TTL)
|
||||
if err != nil || l.Kind != api.DecisionLifetimeTTL || ttl <= 0 || ttl > c.maxTTL {
|
||||
return ErrRefused
|
||||
}
|
||||
// Producer CompleteDecision uses its exact decision instant for both bounds.
|
||||
// RFC3339 output can truncate subsecond precision, so do not invent lost time.
|
||||
if !begin.Equal(decision) || end.Sub(begin) != ttl {
|
||||
return ErrRefused
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameSubject(a, b api.SubjectRef) bool {
|
||||
return a.ID == b.ID && a.Type == b.Type && a.Tenant == b.Tenant
|
||||
}
|
||||
func sameResource(a, b api.ResourceRef) bool {
|
||||
return a.ID == b.ID && a.Type == b.Type && a.System == b.System && a.Tenant == b.Tenant
|
||||
}
|
||||
|
|
@ -0,0 +1,211 @@
|
|||
package decisionpep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
type transportFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func testClient(t *testing.T) (*Client, ed25519.PrivateKey, time.Time) {
|
||||
t.Helper()
|
||||
pub, key, e := ed25519.GenerateKey(rand.Reader)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
now := time.Date(2026, 10, 18, 1, 2, 3, 0, time.UTC)
|
||||
dir := t.TempDir()
|
||||
cert, e := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}, &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}, pub, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ca := filepath.Join(dir, "ca.pem")
|
||||
token := filepath.Join(dir, "token")
|
||||
if e = os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0600); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = os.WriteFile(token, []byte("synthetic-caller-token"), 0600); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a := Admission{Endpoint: "https://pdp.invalid/v1/check", CAFile: ca, TokenFile: token, Keys: map[string]string{"test-key": base64.RawURLEncoding.EncodeToString(pub)}, Evaluator: "flex-auth/local", PolicyPackage: "forgejo.application-access", PolicyVersion: "v1", PolicyDigest: "sha256:" + strings.Repeat("1", 64), RegistryDigest: "sha256:" + strings.Repeat("2", 64), CallerPrincipal: "system:serviceaccount:test:forgejo", CallerAudience: "access-engine", MaxTTL: "30s", MaxClockSkew: "1s"}
|
||||
c, e := New(a)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.now = func() time.Time { return now }
|
||||
return c, key, now
|
||||
}
|
||||
func testRequest() api.CheckRequest {
|
||||
return api.CheckRequest{Tenant: "tenant:test", Subject: api.SubjectRef{ID: "subject:test", Type: api.SubjectType("Human"), Tenant: "tenant:test", Attributes: map[string]any{"groups": []string{"engineers"}}}, Action: "application.access", Resource: api.ResourceRef{ID: "application:forgejo", Type: "application", System: "forgejo", Tenant: "tenant:test"}, Context: map[string]any{"big": json.Number("9007199254740993"), "fraction": json.Number("0.123456789123456789")}}
|
||||
}
|
||||
func envelope(c *Client, r api.CheckRequest, key ed25519.PrivateKey, now time.Time) api.DecisionEnvelope {
|
||||
e := api.DecisionEnvelope{ID: "test-decision", RequestID: r.ID, Effect: api.DecisionEffectAllow, MatchedPolicyVersion: c.admission.PolicyVersion, Subject: r.Subject, Resource: r.Resource, Binding: api.NewDecisionBindingFor(r, r), Provenance: api.DecisionProvenance{Evaluator: c.admission.Evaluator, Mode: provenanceMode, PolicyPackage: c.admission.PolicyPackage, PolicyVersion: c.admission.PolicyVersion, PolicyPackageDigest: c.admission.PolicyDigest, RegistrySnapshotDigest: c.admission.RegistryDigest, Caller: &api.CallerProvenance{Mode: "enforce", Principal: c.admission.CallerPrincipal, Audience: c.admission.CallerAudience, NotAfter: now.Add(time.Minute).Format(time.RFC3339Nano)}}}
|
||||
api.CompleteDecision(&e, r, api.DecisionCompletion{AllowTTL: "10s", Now: now})
|
||||
if sign.Sign(&e, key, "test-key") != nil {
|
||||
panic("test sign")
|
||||
}
|
||||
return e
|
||||
}
|
||||
func respond(t *testing.T, c *Client, key ed25519.PrivateKey, now time.Time, mutate func(*api.DecisionEnvelope), resign bool) {
|
||||
t.Helper()
|
||||
c.http = &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if req.Header.Get("Access-Engine-JSON-Profile") != JSONProfile {
|
||||
t.Fatal("missing lossless profile")
|
||||
}
|
||||
if req.Header.Get("Authorization") != "Bearer synthetic-caller-token" {
|
||||
t.Fatal("wrong synthetic caller token")
|
||||
}
|
||||
var r api.CheckRequest
|
||||
d := json.NewDecoder(req.Body)
|
||||
d.UseNumber()
|
||||
if d.Decode(&r) != nil {
|
||||
t.Fatal("request decode")
|
||||
}
|
||||
if r.Context["big"] != json.Number("9007199254740993") || r.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("request numeric precision lost")
|
||||
}
|
||||
if len(r.Context[nonceKey].(string)) != 64 || r.ID != r.Context[nonceKey] {
|
||||
t.Fatal("nonce")
|
||||
}
|
||||
e := envelope(c, r, key, now)
|
||||
if mutate != nil {
|
||||
mutate(&e)
|
||||
}
|
||||
if resign {
|
||||
if sign.Sign(&e, key, "test-key") != nil {
|
||||
t.Fatal("sign")
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(b))), Header: http.Header{}}, nil
|
||||
})}
|
||||
}
|
||||
func TestAuthenticDecisionProducerCanonicalPrecision(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, nil, false)
|
||||
e, err := c.Check(context.Background(), testRequest())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.Binding.Context["big"] != json.Number("9007199254740993") || e.Binding.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("signed typed precision lost")
|
||||
}
|
||||
if sign.Verify(e, c.keys) != nil {
|
||||
t.Fatal("returned envelope not authentic producer bytes")
|
||||
}
|
||||
}
|
||||
func TestDecisionAdverseBindings(t *testing.T) {
|
||||
cases := map[string]func(*api.DecisionEnvelope){
|
||||
"unsigned": func(e *api.DecisionEnvelope) { e.Signature = api.UnsignedEnvelopeSignature() },
|
||||
"effect": func(e *api.DecisionEnvelope) { e.Effect = api.DecisionEffectDeny },
|
||||
"evaluator": func(e *api.DecisionEnvelope) { e.Provenance.Evaluator = "impostor" },
|
||||
"policy": func(e *api.DecisionEnvelope) { e.Provenance.PolicyPackage = "other" },
|
||||
"version": func(e *api.DecisionEnvelope) { e.Provenance.PolicyVersion = "v2" },
|
||||
"policy-digest": func(e *api.DecisionEnvelope) { e.Provenance.PolicyPackageDigest = "sha256:" + strings.Repeat("3", 64) },
|
||||
"registry": func(e *api.DecisionEnvelope) {
|
||||
e.Provenance.RegistrySnapshotDigest = "sha256:" + strings.Repeat("4", 64)
|
||||
},
|
||||
"tenant": func(e *api.DecisionEnvelope) { e.Binding.Tenant = "other" },
|
||||
"actor": func(e *api.DecisionEnvelope) { e.Binding.Subject.ID = "other" },
|
||||
"action": func(e *api.DecisionEnvelope) { e.Binding.Action = "write" },
|
||||
"resource": func(e *api.DecisionEnvelope) { e.Binding.Resource.ID = "other" },
|
||||
"purpose": func(e *api.DecisionEnvelope) { e.Binding.Purpose = "readback" },
|
||||
"submitted": func(e *api.DecisionEnvelope) { e.Binding.SubmittedRequestDigest = "wrong" },
|
||||
"context": func(e *api.DecisionEnvelope) { e.Binding.Context["fraction"] = json.Number("0.123456789123456788") },
|
||||
"legacy-numeric-profile": func(e *api.DecisionEnvelope) { e.Provenance.Mode = "standalone" },
|
||||
"caller-warn": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Mode = "warn" },
|
||||
"caller-principal": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Principal = "other" },
|
||||
"caller-audience": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Audience = "other" },
|
||||
"caller-expired": func(e *api.DecisionEnvelope) { e.Provenance.Caller.NotAfter = "2020-01-01T00:00:00Z" },
|
||||
"stale-decision": func(e *api.DecisionEnvelope) { e.Provenance.DecisionTime = "2020-01-01T00:00:00Z" },
|
||||
"expired": func(e *api.DecisionEnvelope) { e.Lifetime.ExpiresAt = "2020-01-01T00:00:00Z" },
|
||||
"future-begin": func(e *api.DecisionEnvelope) { e.Lifetime.NotBefore = "2030-01-01T00:00:00Z" },
|
||||
"subnanosecond-expiry": func(e *api.DecisionEnvelope) { e.Lifetime.ExpiresAt = "2026-10-18T01:02:02.999999999Z" },
|
||||
"missing-TTL": func(e *api.DecisionEnvelope) { e.Lifetime = nil },
|
||||
"excess-TTL": func(e *api.DecisionEnvelope) { e.Lifetime.TTL = "1h" },
|
||||
"obligation": func(e *api.DecisionEnvelope) { e.Obligations = []api.Obligation{{Type: "unimplemented"}} },
|
||||
}
|
||||
for name, mutation := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, mutation, name != "unsigned")
|
||||
if _, err := c.Check(context.Background(), testRequest()); err == nil {
|
||||
t.Fatal("accepted wrong signed binding")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestSignatureForgeryAndReplay(t *testing.T) {
|
||||
t.Run("forged-payload", func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, func(e *api.DecisionEnvelope) { e.Reason = "changed after signature" }, false)
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("forgery accepted")
|
||||
}
|
||||
})
|
||||
t.Run("wrong-key", func(t *testing.T) {
|
||||
c, _, now := testClient(t)
|
||||
_, key, _ := ed25519.GenerateKey(rand.Reader)
|
||||
respond(t, c, key, now, nil, false)
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("wrong key accepted")
|
||||
}
|
||||
})
|
||||
t.Run("replay", func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
var saved []byte
|
||||
c.http = &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if saved == nil {
|
||||
var r api.CheckRequest
|
||||
d := json.NewDecoder(req.Body)
|
||||
d.UseNumber()
|
||||
if d.Decode(&r) != nil {
|
||||
t.Fatal("decode")
|
||||
}
|
||||
e := envelope(c, r, key, now)
|
||||
saved, _ = json.Marshal(e)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(saved)))}, nil
|
||||
})}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("old decision replay accepted for new nonce")
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestUnavailableAndPublicTokenFileRefuse(t *testing.T) {
|
||||
c, _, _ := testClient(t)
|
||||
c.http = &http.Client{Transport: transportFunc(func(*http.Request) (*http.Response, error) { return nil, io.ErrUnexpectedEOF })}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("unavailable allowed")
|
||||
}
|
||||
if e := os.Chmod(c.admission.TokenFile, 0644); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("public token file allowed")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"upstream": "github.com/netkingdom/access-engine",
|
||||
"commit": "d328a2601095686f74376d87791bff01e2a3a2a3",
|
||||
"exact_unchanged_files": {
|
||||
"pkg/api/canonical.go": "a122a2e8cd524333b13c5939c7a3685e41efbe47497a64e0c7297c92b7f10d19",
|
||||
"pkg/api/caring.go": "1907156f0f889e7b9e9c14970cf7a86a20d00478a496efaf92c7231f27fec5e3",
|
||||
"pkg/api/resource_manifest.go": "f0fa4080287d389ed48c2b1d6af96cc62e57ef72c902333f677f964420be133f",
|
||||
"internal/sign/sign.go": "0df9515922e90775ebbfac798361dcafb20da8a4213796b44e246b8a92046cde",
|
||||
"LICENSE": "ff413f361a3b3bf44cf50f110fbcc4837064d57eefbcef89df2b43997c6262b6"
|
||||
},
|
||||
"module": "Standalone Go1.24 source slice with original module/import identity; no canonical/schema/signature modifications",
|
||||
"new_code": [
|
||||
"pkg/decisionpep/client.go"
|
||||
],
|
||||
"fixture_code": [
|
||||
"testsupport/signfixture/sign.go"
|
||||
],
|
||||
"source_of_truth": "repository root; generated with tools/export_decisionpep_adapter.py",
|
||||
"exported_file_sha256": {
|
||||
"LICENSE": "ff413f361a3b3bf44cf50f110fbcc4837064d57eefbcef89df2b43997c6262b6",
|
||||
"go.mod": "fea700810e47c1ba5638b86a168f8531c083a6e1222ca80bd2a8947b2ea6f2c3",
|
||||
"internal/sign/sign.go": "0df9515922e90775ebbfac798361dcafb20da8a4213796b44e246b8a92046cde",
|
||||
"pkg/api/canonical.go": "a122a2e8cd524333b13c5939c7a3685e41efbe47497a64e0c7297c92b7f10d19",
|
||||
"pkg/api/caring.go": "1907156f0f889e7b9e9c14970cf7a86a20d00478a496efaf92c7231f27fec5e3",
|
||||
"pkg/api/resource_manifest.go": "f0fa4080287d389ed48c2b1d6af96cc62e57ef72c902333f677f964420be133f",
|
||||
"pkg/decisionpep/client.go": "0d57f6ddaca5c3f81ce426c0e8b14ba14ea5962096d3be5909aa456eef19eeba",
|
||||
"pkg/decisionpep/client_test.go": "1a6be3485f580f95a1f1406fb76e525f2c4bf02fe04a424cfe0095bb728e3f62",
|
||||
"testsupport/signfixture/sign.go": "fe4aa86f444dc20145aefbaca35b24f046264b2c5c8b4e3b057a4496b77a4d29"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
// Package signfixture exposes producer signing only for synthetic consumer tests.
|
||||
// Callers supply test keys; this package contains no credentials or runtime signer.
|
||||
package signfixture
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// Sign uses the unchanged producer envelope format with a caller-owned fixture key.
|
||||
func Sign(envelope *api.DecisionEnvelope, key ed25519.PrivateKey, kid string) error {
|
||||
return sign.Sign(envelope, key, kid)
|
||||
}
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/callerauth"
|
||||
"github.com/netkingdom/access-engine/internal/decision"
|
||||
"github.com/netkingdom/access-engine/internal/policy"
|
||||
"github.com/netkingdom/access-engine/internal/registry"
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
"github.com/netkingdom/access-engine/pkg/decisionpep"
|
||||
)
|
||||
|
||||
type forgejoSyntheticReviewer struct{}
|
||||
|
||||
func (forgejoSyntheticReviewer) Review(_ context.Context, token string) (callerauth.Identity, error) {
|
||||
if token != "synthetic-forgejo-caller" {
|
||||
return callerauth.Identity{}, callerauth.ErrUnauthenticated
|
||||
}
|
||||
return callerauth.Identity{Username: "system:serviceaccount:synthetic:forgejo", Audiences: []string{"access-engine"}, NotAfter: time.Now().Add(time.Minute)}, nil
|
||||
}
|
||||
func forgejoRequest(group string) api.CheckRequest {
|
||||
groups := []string{group}
|
||||
return api.CheckRequest{Tenant: "tenant:synthetic", Subject: api.SubjectRef{ID: "user:synthetic", Type: "human", Tenant: "tenant:synthetic", Attributes: map[string]any{"issuer": "https://issuer.invalid", "assurance": "aal2", "current_userinfo_groups": groups}}, Action: "application.access", Resource: api.ResourceRef{ID: "application:forgejo", Type: "application", System: "forgejo", Tenant: "tenant:synthetic"}, Context: map[string]any{"identity_tenant": "tenant:synthetic", "identity_subject": "user:synthetic", "identity_principal_type": "human", "identity_issuer": "https://issuer.invalid", "identity_assurance": "aal2", "current_userinfo_groups": groups, "required_groups_any_of": []string{"forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"}, "big": json.Number("9007199254740993"), "fraction": json.Number("0.123456789123456789")}}
|
||||
}
|
||||
|
||||
func TestForgejoActualPolicySignedLosslessAndLegacy(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
pkg, e := policy.LoadAndValidateFile(ctx, filepath.Join("..", "..", "examples", "forgejo-application-access", "policy.md"))
|
||||
if e != nil || !pkg.Valid {
|
||||
t.Fatalf("policy: %v %+v", e, pkg)
|
||||
}
|
||||
store, e := registry.LoadFilePreservingNumbers(filepath.Join("..", "..", "examples", "forgejo-application-access", "registry_snapshot.json"))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
engine, e := decision.NewEngine(store, pkg)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
pub, key, e := ed25519.GenerateKey(rand.Reader)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = engine.SetEnvelopeSigningKey(key, "synthetic-pdp"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
auth, e := callerauth.New(callerauth.ModeEnforce, forgejoSyntheticReviewer{}, "access-engine", map[string]string{"forgejo": "system:serviceaccount:synthetic:forgejo"}, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
server := httptest.NewTLSServer(newServeMuxWithCallerAuth(engine, auth))
|
||||
defer server.Close()
|
||||
folder := t.TempDir()
|
||||
ca := filepath.Join(folder, "ca.pem")
|
||||
token := filepath.Join(folder, "token")
|
||||
os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600)
|
||||
os.WriteFile(token, []byte("synthetic-forgejo-caller"), 0600)
|
||||
admitted := decisionpep.Admission{Endpoint: server.URL + "/v1/check", CAFile: ca, TokenFile: token, Keys: map[string]string{"synthetic-pdp": base64.RawURLEncoding.EncodeToString(pub)}, Evaluator: "flex-auth/local", PolicyPackage: pkg.Metadata.ID, PolicyVersion: pkg.Metadata.Version, PolicyDigest: pkg.Digest(), RegistryDigest: store.Digest(), CallerPrincipal: "system:serviceaccount:synthetic:forgejo", CallerAudience: "access-engine", MaxTTL: "30s", MaxClockSkew: "2s"}
|
||||
client, e := decisionpep.New(admitted)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, g := range []string{"forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"} {
|
||||
t.Run(g, func(t *testing.T) {
|
||||
got, e := client.Check(ctx, forgejoRequest(g))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if got.Binding.Context["big"] != json.Number("9007199254740993") || got.Binding.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("actual producer numeric precision lost")
|
||||
}
|
||||
if got.Provenance.Mode != "standalone/lossless-json-v1" || sign.Verify(got, map[string]ed25519.PublicKey{"synthetic-pdp": pub}) != nil {
|
||||
t.Fatal("actual producer profile not authenticated")
|
||||
}
|
||||
})
|
||||
}
|
||||
for name, mutate := range map[string]func(*api.CheckRequest){"object-current-groups": func(r *api.CheckRequest) {
|
||||
r.Context["current_userinfo_groups"] = map[string]any{"key": "forge-admins"}
|
||||
}, "object-required-groups": func(r *api.CheckRequest) {
|
||||
r.Context["required_groups_any_of"] = map[string]any{"a": "forge-admins", "b": "forge-coulomb-owners", "c": "forge-coulomb-readers"}
|
||||
}, "outsider": func(r *api.CheckRequest) {
|
||||
r.Context["current_userinfo_groups"] = []string{"outsider"}
|
||||
r.Subject.Attributes["current_userinfo_groups"] = []string{"outsider"}
|
||||
}, "empty-current-groups": func(r *api.CheckRequest) {
|
||||
r.Context["current_userinfo_groups"] = []string{}
|
||||
r.Subject.Attributes["current_userinfo_groups"] = []string{}
|
||||
}, "wrong-tenant": func(r *api.CheckRequest) {
|
||||
r.Tenant = "tenant:other"
|
||||
r.Subject.Tenant = r.Tenant
|
||||
r.Resource.Tenant = r.Tenant
|
||||
r.Context["identity_tenant"] = r.Tenant
|
||||
}, "wrong-issuer": func(r *api.CheckRequest) {
|
||||
r.Subject.Attributes["issuer"] = "https://other.invalid"
|
||||
r.Context["identity_issuer"] = "https://other.invalid"
|
||||
}, "forged-resource-issuer": func(r *api.CheckRequest) {
|
||||
r.Context["identity_issuer"] = "https://other.invalid"
|
||||
r.Resource.Attributes = map[string]any{"identity_issuer": "https://other.invalid", "tenant": "tenant:synthetic"}
|
||||
}, "wrong-assurance": func(r *api.CheckRequest) {
|
||||
r.Subject.Attributes["assurance"] = "aal1"
|
||||
r.Context["identity_assurance"] = "aal1"
|
||||
}, "wrong-action": func(r *api.CheckRequest) { r.Action = "source.operation" }, "wrong-resource": func(r *api.CheckRequest) { r.Resource.ID = "application:unregistered" }, "claim-shortcut": func(r *api.CheckRequest) {
|
||||
r.Context["required_groups_any_of"] = []string{"outsider"}
|
||||
r.Context["current_userinfo_groups"] = []string{"outsider"}
|
||||
r.Subject.Attributes["current_userinfo_groups"] = []string{"outsider"}
|
||||
}} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
r := forgejoRequest("forge-admins")
|
||||
mutate(&r)
|
||||
if _, e := client.Check(ctx, r); e == nil {
|
||||
t.Fatal("actual PDP allowed adverse input")
|
||||
}
|
||||
})
|
||||
}
|
||||
// A caller-provided JSON key cannot install the producer's private Go context
|
||||
// key. This path uses the actual normal handler, not a constructed envelope.
|
||||
r := forgejoRequest("forge-admins")
|
||||
r.Context["decisionpep_request_nonce"] = strings.Repeat("0", 64)
|
||||
r.Context["decisionpep_json_profile"] = decisionpep.JSONProfile
|
||||
r.Context["jsonProfileContextKey"] = decisionpep.JSONProfile
|
||||
raw, _ := json.Marshal(r)
|
||||
for _, profile := range []string{"", decisionpep.JSONProfile, "unknown"} {
|
||||
req, _ := http.NewRequest(http.MethodPost, server.URL+"/v1/check", bytes.NewReader(raw))
|
||||
req.Header.Set("Authorization", "Bearer synthetic-forgejo-caller")
|
||||
if profile != "" {
|
||||
req.Header.Set("Access-Engine-JSON-Profile", profile)
|
||||
}
|
||||
response, e := server.Client().Do(req)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
if profile == "unknown" {
|
||||
if response.StatusCode != 400 {
|
||||
t.Fatal("unknown profile not refused")
|
||||
}
|
||||
continue
|
||||
}
|
||||
e1, e := sign.DecodeEnvelope(body)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if sign.Verify(e1, map[string]ed25519.PublicKey{"synthetic-pdp": pub}) != nil {
|
||||
t.Fatal("producer signature")
|
||||
}
|
||||
if profile == "" {
|
||||
if e1.Provenance.Mode != "standalone" {
|
||||
t.Fatal("caller JSON spoofed producer profile")
|
||||
}
|
||||
if e1.Binding.SubmittedRequestDigest == api.RequestDigest(r) {
|
||||
t.Fatal("legacy numeric projection unexpectedly changed")
|
||||
}
|
||||
} else {
|
||||
if e1.Provenance.Mode != "standalone/lossless-json-v1" || e1.Binding.SubmittedRequestDigest != api.RequestDigest(r) {
|
||||
t.Fatal("lossless submitted binding mismatch")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,770 @@
|
|||
// Command flex-auth is the CLI entry point for the flex-auth authorization
|
||||
// registry and control plane.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/audit"
|
||||
"github.com/netkingdom/access-engine/internal/callerauth"
|
||||
decisioncore "github.com/netkingdom/access-engine/internal/decision"
|
||||
"github.com/netkingdom/access-engine/internal/emission"
|
||||
"github.com/netkingdom/access-engine/internal/policy"
|
||||
"github.com/netkingdom/access-engine/internal/registry"
|
||||
"github.com/netkingdom/access-engine/internal/taskexecution"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// version is set at build time via -ldflags "-X main.version=...".
|
||||
var version = "0.0.0-dev"
|
||||
|
||||
func main() {
|
||||
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
|
||||
}
|
||||
|
||||
func run(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
printUsage(stderr)
|
||||
return 64
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "version", "--version", "-version":
|
||||
fmt.Fprintln(stdout, version)
|
||||
return 0
|
||||
case "validate":
|
||||
return runValidate(args[1:], stdout, stderr)
|
||||
case "load-registry":
|
||||
return runLoadRegistry(args[1:], stdout, stderr)
|
||||
case "test-policy":
|
||||
return runTestPolicy(args[1:], stdout, stderr)
|
||||
case "check":
|
||||
return runCheck(args[1:], stdout, stderr)
|
||||
case "batch-check":
|
||||
return runBatchCheck(args[1:], stdout, stderr)
|
||||
case "list-allowed":
|
||||
return runListAllowed(args[1:], stdout, stderr)
|
||||
case "explain":
|
||||
return runExplain(args[1:], stdout, stderr)
|
||||
case "serve":
|
||||
return runServe(args[1:], stdout, stderr)
|
||||
case "serve-readback":
|
||||
return runServeReadback(args[1:], stdout, stderr)
|
||||
case "help", "-h", "--help":
|
||||
printUsage(stdout)
|
||||
return 0
|
||||
default:
|
||||
fmt.Fprintf(stderr, "access-engine: unknown subcommand %q\n", args[0])
|
||||
printUsage(stderr)
|
||||
return 64
|
||||
}
|
||||
}
|
||||
|
||||
func runValidate(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("validate", stderr)
|
||||
kind := fs.String("kind", "", "resource-manifest, subject-manifest, protected-system, relationship, access-descriptor, or policy")
|
||||
file := fs.String("file", "", "YAML/JSON file to validate")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *kind == "" || *file == "" {
|
||||
fmt.Fprintln(stderr, "validate requires --kind and --file")
|
||||
return 64
|
||||
}
|
||||
|
||||
switch *kind {
|
||||
case "resource-manifest":
|
||||
var manifest api.ResourceManifest
|
||||
if err := readYAML(*file, &manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().ImportResourceManifest(manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "subject-manifest":
|
||||
var manifest api.SubjectManifest
|
||||
if err := readYAML(*file, &manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().ImportSubjectManifest(manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "protected-system":
|
||||
var manifest api.ProtectedSystemManifest
|
||||
if err := readYAML(*file, &manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().PutProtectedSystem(manifest); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "relationship":
|
||||
var fact api.RelationshipFact
|
||||
if err := readYAML(*file, &fact); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := registry.NewStore().PutRelationship(fact); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "access-descriptor":
|
||||
var descriptor api.CaringAccessDescriptor
|
||||
if err := readYAML(*file, &descriptor); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := validateDescriptor(descriptor); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
case "policy", "policy-package":
|
||||
pkg, err := policy.LoadAndValidateFile(context.Background(), *file)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, pkg.Validation); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if !pkg.Valid {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
default:
|
||||
fmt.Fprintf(stderr, "unsupported validate kind %q\n", *kind)
|
||||
return 64
|
||||
}
|
||||
|
||||
return writeStatus(stdout, "valid", map[string]any{"kind": *kind, "file": *file})
|
||||
}
|
||||
|
||||
func runLoadRegistry(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("load-registry", stderr)
|
||||
file := fs.String("file", "", "registry snapshot JSON file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *file == "" {
|
||||
fmt.Fprintln(stderr, "load-registry requires --file")
|
||||
return 64
|
||||
}
|
||||
|
||||
store, err := registry.LoadFile(*file)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
snapshot := store.Snapshot()
|
||||
return writeStatus(stdout, "loaded", map[string]any{
|
||||
"file": *file,
|
||||
"systems": len(snapshot.Systems),
|
||||
"resource_manifests": len(snapshot.ResourceManifests),
|
||||
"subjects": len(snapshot.Subjects),
|
||||
"groups": len(snapshot.Groups),
|
||||
"teams": len(snapshot.Teams),
|
||||
"tenants": len(snapshot.Tenants),
|
||||
"relationships": len(snapshot.Relationships),
|
||||
})
|
||||
}
|
||||
|
||||
func runTestPolicy(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("test-policy", stderr)
|
||||
file := fs.String("file", "", "policy package Markdown file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *file == "" {
|
||||
fmt.Fprintln(stderr, "test-policy requires --file")
|
||||
return 64
|
||||
}
|
||||
|
||||
pkg, err := policy.LoadAndValidateFile(context.Background(), *file)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, pkg.Validation); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if !pkg.Valid {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runCheck(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("check", stderr)
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
requestPath := fs.String("request", "", "check request YAML/JSON file")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" || *requestPath == "" {
|
||||
fmt.Fprintln(stderr, "check requires --registry, --policy, and --request")
|
||||
return 64
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var request api.CheckRequest
|
||||
if err := readYAML(*requestPath, &request); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
decision, err := engine.Check(context.Background(), request)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, decision); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runBatchCheck(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("batch-check", stderr)
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
requestPath := fs.String("request", "", "batch check request YAML/JSON file")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" || *requestPath == "" {
|
||||
fmt.Fprintln(stderr, "batch-check requires --registry, --policy, and --request")
|
||||
return 64
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var request api.BatchCheckRequest
|
||||
if err := readYAML(*requestPath, &request); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
decisions, err := engine.BatchCheck(context.Background(), request)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, decisions); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runListAllowed(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("list-allowed", stderr)
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
subject := fs.String("subject", "", "subject id")
|
||||
action := fs.String("action", "", "action name")
|
||||
system := fs.String("system", "", "protected system id")
|
||||
resourceType := fs.String("resource-type", "", "resource type")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
var filters keyValueFlags
|
||||
fs.Var(&filters, "filter", "resource filter as key=value; may be repeated")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" || *subject == "" || *action == "" {
|
||||
fmt.Fprintln(stderr, "list-allowed requires --registry, --policy, --subject, and --action")
|
||||
return 64
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
decisions, err := engine.ListAllowed(context.Background(), decisioncore.ListAllowedRequest{
|
||||
Subject: api.SubjectRef{ID: *subject},
|
||||
Action: *action,
|
||||
System: *system,
|
||||
ResourceType: *resourceType,
|
||||
Filters: filters.Map(),
|
||||
})
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := writeJSON(stdout, decisions); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runExplain(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("explain", stderr)
|
||||
logPath := fs.String("decision-log", "", "JSONL decision log path")
|
||||
decisionID := fs.String("decision-id", "", "decision id to explain")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *logPath == "" || *decisionID == "" {
|
||||
fmt.Fprintln(stderr, "explain requires --decision-log and --decision-id")
|
||||
return 64
|
||||
}
|
||||
|
||||
log := audit.NewJSONLDecisionLog(*logPath)
|
||||
envelope, ok, err := log.Find(*decisionID)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if !ok {
|
||||
return fail(stderr, fmt.Errorf("decision %q not found", *decisionID))
|
||||
}
|
||||
if err := writeJSON(stdout, decisioncore.ExplainEnvelope(envelope)); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runServe(args []string, stdout, stderr io.Writer) int {
|
||||
fs := newFlagSet("serve", stderr)
|
||||
addr := fs.String("addr", "127.0.0.1:8080", "HTTP listen address")
|
||||
registryPath := fs.String("registry", "", "registry snapshot JSON file")
|
||||
policyPath := fs.String("policy", "", "policy package Markdown file")
|
||||
logPath := fs.String("log", "", "optional JSONL decision log path")
|
||||
signingKeyFile := fs.String("envelope-signing-key-file", "", "owner-mounted base64url Ed25519 seed file")
|
||||
signingKID := fs.String("envelope-signing-kid", "", "independently admitted envelope signing key id")
|
||||
approvalSourceFile := fs.String("approval-source-file", "", "owner fixed Approval HTTPS reader configuration file")
|
||||
outboxMaxBytes := fs.Int64("outbox-max-bytes", emission.MaxOutboxBytes, "bounded outbox payload bytes, maximum67108864")
|
||||
outboxDir := fs.String("outbox-dir", "", "durable emission outbox directory (FLEX-WP-0031); exclusive with --log")
|
||||
emissionSource := fs.String("emission-source", "", "audit-core source name for emitted decision events, e.g. flex-auth.tenant-engine")
|
||||
auditURL := fs.String("audit-url", "", "admitted audit-core /v1/events endpoint; empty disables drain and heartbeats")
|
||||
auditTokenFile := fs.String("audit-token-file", "", "mounted sender token file, never a token value")
|
||||
callerAuthMode := fs.String("caller-auth-mode", "disabled", "disabled, warn, or enforce")
|
||||
callerAudience := fs.String("caller-audience", "flex-auth", "required caller token audience")
|
||||
callerKubernetesURL := fs.String("caller-kubernetes-url", "https://kubernetes.default.svc", "Kubernetes API base URL for TokenReview")
|
||||
callerReviewerTokenFile := fs.String("caller-reviewer-token-file", "/var/run/secrets/flex-auth-reviewer/token", "projected Kubernetes API credential")
|
||||
callerCAFile := fs.String("caller-ca-file", "/var/run/secrets/flex-auth-reviewer/ca.crt", "Kubernetes API CA bundle")
|
||||
var callerBindings keyValueFlags
|
||||
fs.Var(&callerBindings, "caller-binding", "resource system=authenticated Kubernetes principal (repeatable)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 64
|
||||
}
|
||||
if *registryPath == "" || *policyPath == "" {
|
||||
fmt.Fprintln(stderr, "serve requires --registry and --policy")
|
||||
return 64
|
||||
}
|
||||
|
||||
if *outboxDir != "" && (*logPath != "" || *emissionSource == "") {
|
||||
fmt.Fprintln(stderr, "serve --outbox-dir requires --emission-source and excludes --log")
|
||||
return 64
|
||||
}
|
||||
delivery := emission.DeliveryConfig{URL: *auditURL, TokenFile: *auditTokenFile}
|
||||
if *auditURL != "" || *auditTokenFile != "" {
|
||||
if *outboxDir == "" {
|
||||
fmt.Fprintln(stderr, "audit delivery requires --outbox-dir")
|
||||
return 64
|
||||
}
|
||||
if err := delivery.Validate(); err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return 64
|
||||
}
|
||||
}
|
||||
|
||||
engine, err := buildEngine(context.Background(), *registryPath, *policyPath, *logPath)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
if err := configureEnvelopeSigning(engine, *signingKeyFile, *signingKID); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var outbox *emission.Outbox
|
||||
if *outboxDir != "" {
|
||||
outbox, err = emission.OpenBounded(*outboxDir, *emissionSource, *outboxMaxBytes)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
defer outbox.Close()
|
||||
engine.SetDecisionLog(outbox)
|
||||
}
|
||||
|
||||
authenticator, err := buildCallerAuthenticator(
|
||||
callerauth.Mode(*callerAuthMode),
|
||||
*callerAudience,
|
||||
*callerKubernetesURL,
|
||||
*callerReviewerTokenFile,
|
||||
*callerCAFile,
|
||||
callerBindings.StringMap(),
|
||||
stderr,
|
||||
)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
|
||||
serviceInputs, err := buildServicePilotInputs(engine, callerauth.Mode(*callerAuthMode), *callerAudience, *callerKubernetesURL, *callerReviewerTokenFile, *callerCAFile, callerBindings.StringMap())
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
var approvalReader *taskexecution.ApprovalReader
|
||||
if engine.IsTrustedServicePilot() {
|
||||
if *signingKeyFile == "" || *approvalSourceFile == "" {
|
||||
return fail(stderr, fmt.Errorf("trusted task source requires signing and fixed Approval reader configuration"))
|
||||
}
|
||||
approvalReader, err = taskexecution.LoadApprovalReader(*approvalSourceFile)
|
||||
if err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
} else if *approvalSourceFile != "" {
|
||||
return fail(stderr, fmt.Errorf("Approval reader requires exact trusted task source package"))
|
||||
}
|
||||
mux := newServeMuxWithTaskFacts(engine, authenticator, serviceInputs, approvalReader)
|
||||
if outbox != nil {
|
||||
mountEmission(mux, outbox)
|
||||
}
|
||||
if *auditURL != "" {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
runEmissionDelivery(ctx, outbox, delivery, stderr)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
}
|
||||
|
||||
fmt.Fprintf(stderr, "access-engine serving on http://%s\n", *addr)
|
||||
if err := http.ListenAndServe(*addr, mux); err != nil {
|
||||
return fail(stderr, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func runEmissionDelivery(ctx context.Context, outbox *emission.Outbox, config emission.DeliveryConfig, stderr io.Writer) {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := outbox.AppendDueHeartbeats(); err != nil {
|
||||
fmt.Fprintf(stderr, "emission heartbeat commit: %v\n", err)
|
||||
}
|
||||
n, err := outbox.Drain(ctx, config, 100)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
fmt.Fprintf(stderr, "emission drain: %v\n", err)
|
||||
}
|
||||
if err == nil && n == 100 {
|
||||
continue // Drain the next bounded batch without imposing a rate cap.
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newServeMux(engine *decisioncore.Engine) *http.ServeMux {
|
||||
return newServeMuxWithCallerAuth(engine, callerauth.Disabled())
|
||||
}
|
||||
|
||||
func newServeMuxWithCallerAuth(engine *decisioncore.Engine, authenticator *callerauth.Authenticator) *http.ServeMux {
|
||||
return newServeMuxWithServicePilotInputs(engine, authenticator, nil)
|
||||
}
|
||||
|
||||
func newServeMuxWithServicePilotInputs(engine *decisioncore.Engine, authenticator *callerauth.Authenticator, serviceInputs *taskexecution.ServicePilotInputs) *http.ServeMux {
|
||||
return newServeMuxWithTaskFacts(engine, authenticator, serviceInputs, nil)
|
||||
}
|
||||
func newServeMuxWithTaskFacts(engine *decisioncore.Engine, authenticator *callerauth.Authenticator, serviceInputs *taskexecution.ServicePilotInputs, approvalReader *taskexecution.ApprovalReader) *http.ServeMux {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
})
|
||||
mux.HandleFunc("/v1/check", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if engine.IsTaskPin() {
|
||||
if serviceInputs == nil {
|
||||
http.Error(w, "service input unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
decode := taskexecution.DecodeServiceRequest
|
||||
if engine.IsTrustedServicePilot() {
|
||||
decode = taskexecution.DecodeTrustedServiceRequest
|
||||
}
|
||||
request, err := decode(r.Body)
|
||||
if err != nil || request.Purpose != "" {
|
||||
http.Error(w, "invalid service task request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
input, err := serviceInputs.Prepare(r.Context(), r.Header.Get("Authorization"), request, time.Now().UTC())
|
||||
if err != nil {
|
||||
http.Error(w, "service task input refused", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
var decision api.DecisionEnvelope
|
||||
if engine.IsTrustedServicePilot() {
|
||||
decision, err = engine.CheckTrustedService(r.Context(), input, approvalReader)
|
||||
} else {
|
||||
decision, err = engine.CheckServicePilot(r.Context(), input)
|
||||
}
|
||||
writeHTTP(w, decision, err)
|
||||
return
|
||||
}
|
||||
profile := r.Header.Get("Access-Engine-JSON-Profile")
|
||||
if profile != "" && profile != decisioncore.LosslessJSONProfile {
|
||||
http.Error(w, "unsupported JSON numeric profile", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var request api.CheckRequest
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if profile == decisioncore.LosslessJSONProfile {
|
||||
decoder.UseNumber()
|
||||
}
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if request.Purpose != "" {
|
||||
// Only the readback pin issues purpose-bearing decisions
|
||||
// (FLEX-DEC-2026-019); an enforcement pin never does.
|
||||
http.Error(w, "purpose is not accepted on /v1/check", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
identity, err := authenticator.Authorize(r.Context(), r.Header.Get("Authorization"), []string{request.Resource.System})
|
||||
if err != nil {
|
||||
writeCallerAuthError(w, err)
|
||||
return
|
||||
}
|
||||
decisionContext := callerauth.WithRecord(r.Context(), authenticator.Record(identity))
|
||||
if profile == decisioncore.LosslessJSONProfile {
|
||||
decisionContext = decisioncore.WithLosslessJSONProfile(decisionContext)
|
||||
}
|
||||
decision, err := engine.Check(decisionContext, request)
|
||||
writeHTTP(w, decision, err)
|
||||
})
|
||||
mux.HandleFunc("/v1/batch_check", func(w http.ResponseWriter, r *http.Request) {
|
||||
if engine.IsTaskPin() {
|
||||
http.Error(w, "service task batch unavailable", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var request api.BatchCheckRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
systems := make([]string, 0, len(request.Resources))
|
||||
for _, resource := range request.Resources {
|
||||
systems = append(systems, resource.System)
|
||||
}
|
||||
identity, err := authenticator.Authorize(r.Context(), r.Header.Get("Authorization"), systems)
|
||||
if err != nil {
|
||||
writeCallerAuthError(w, err)
|
||||
return
|
||||
}
|
||||
decisions, err := engine.BatchCheck(callerauth.WithRecord(r.Context(), authenticator.Record(identity)), request)
|
||||
writeHTTP(w, decisions, err)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
// Only the existing exact service pilot package selects this source path.
|
||||
// This is not an eligibility toggle; successful preparation still only DENYs.
|
||||
func buildServicePilotInputs(engine *decisioncore.Engine, mode callerauth.Mode, audience, kubernetesURL, reviewerTokenFile, caFile string, bindings map[string]string) (*taskexecution.ServicePilotInputs, error) {
|
||||
if !engine.IsTaskPin() {
|
||||
return nil, nil
|
||||
}
|
||||
if mode != callerauth.ModeEnforce || audience != "flex-auth" || len(bindings) != 1 || bindings["secrets-engine"] != taskexecution.ServicePilotPrincipal {
|
||||
return nil, fmt.Errorf("service pilot requires exact enforced retained caller mapping")
|
||||
}
|
||||
reviewer, err := callerauth.NewKubernetesTokenReviewer(kubernetesURL, audience, reviewerTokenFile, caFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if engine.IsTrustedServicePilot() {
|
||||
return taskexecution.NewTrustedServiceInputs(reviewer)
|
||||
}
|
||||
return taskexecution.NewServicePilotInputs(reviewer)
|
||||
}
|
||||
|
||||
func buildCallerAuthenticator(mode callerauth.Mode, audience, kubernetesURL, reviewerTokenFile, caFile string, bindings map[string]string, stderr io.Writer) (*callerauth.Authenticator, error) {
|
||||
if mode == callerauth.ModeDisabled {
|
||||
return callerauth.New(mode, nil, "", nil, nil)
|
||||
}
|
||||
reviewer, err := callerauth.NewKubernetesTokenReviewer(kubernetesURL, audience, reviewerTokenFile, caFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return callerauth.New(mode, reviewer, audience, bindings, func(format string, args ...any) {
|
||||
fmt.Fprintf(stderr, format+"\n", args...)
|
||||
})
|
||||
}
|
||||
|
||||
func writeCallerAuthError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, callerauth.ErrUnauthenticated):
|
||||
http.Error(w, "unauthenticated", http.StatusUnauthorized)
|
||||
case errors.Is(err, callerauth.ErrForbidden):
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
default:
|
||||
http.Error(w, "caller authentication unavailable", http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func buildEngine(ctx context.Context, registryPath, policyPath, logPath string) (*decisioncore.Engine, error) {
|
||||
pkg, err := policy.LoadAndValidateFile(ctx, policyPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load := registry.LoadFile
|
||||
if pkg.Metadata.ID == taskexecution.ServicePilotPackageID && pkg.Metadata.Version == taskexecution.TrustedServicePilotPackageVersion {
|
||||
load = registry.LoadFilePreservingNumbers
|
||||
}
|
||||
store, err := load(registryPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
engine, err := decisioncore.NewEngine(store, pkg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if logPath != "" {
|
||||
engine.SetDecisionLog(audit.NewJSONLDecisionLog(logPath))
|
||||
}
|
||||
return engine, nil
|
||||
}
|
||||
|
||||
func validateDescriptor(descriptor api.CaringAccessDescriptor) error {
|
||||
if descriptor.Profile != api.CaringProfileCaring040RC2 {
|
||||
return fmt.Errorf("unsupported CARING profile %q", descriptor.Profile)
|
||||
}
|
||||
if descriptor.SubjectType == "" {
|
||||
return fmt.Errorf("subject_type is required")
|
||||
}
|
||||
if descriptor.OrganizationRelation == "" {
|
||||
return fmt.Errorf("organization_relation is required")
|
||||
}
|
||||
if descriptor.CanonicalRole == "" {
|
||||
return fmt.Errorf("canonical_role is required")
|
||||
}
|
||||
if descriptor.Scope.Level == "" || descriptor.Scope.ID == "" {
|
||||
return fmt.Errorf("scope.level and scope.id are required")
|
||||
}
|
||||
if len(descriptor.Planes) == 0 {
|
||||
return fmt.Errorf("at least one plane is required")
|
||||
}
|
||||
if len(descriptor.Capabilities) == 0 {
|
||||
return fmt.Errorf("at least one capability is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readYAML(path string, out any) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := yaml.Unmarshal(data, out); err != nil {
|
||||
return fmt.Errorf("unmarshal %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w io.Writer, value any) error {
|
||||
encoder := json.NewEncoder(w)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(value); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeStatus(w io.Writer, status string, extra map[string]any) int {
|
||||
out := map[string]any{"status": status}
|
||||
for key, value := range extra {
|
||||
out[key] = value
|
||||
}
|
||||
if err := writeJSON(w, out); err != nil {
|
||||
return fail(w, err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// mountEmission exposes the local half of reconciliation: committed and
|
||||
// released-uncommitted counts per class. Counts only, never records.
|
||||
func mountEmission(mux *http.ServeMux, outbox *emission.Outbox) {
|
||||
mux.HandleFunc("/v1/emission", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
writeHTTP(w, outbox.Status(), nil)
|
||||
})
|
||||
}
|
||||
|
||||
func writeHTTP(w http.ResponseWriter, value any, err error) {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
if errors.Is(err, decisioncore.ErrRecordNotCommitted) || errors.Is(err, decisioncore.ErrServicePilotUnavailable) {
|
||||
// Unavailable evaluation is not an authorization verdict (GH-DEC-2026-024).
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func newFlagSet(name string, stderr io.Writer) *flag.FlagSet {
|
||||
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
return fs
|
||||
}
|
||||
|
||||
func fail(stderr io.Writer, err error) int {
|
||||
fmt.Fprintln(stderr, "access-engine:", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
func printUsage(w io.Writer) {
|
||||
fmt.Fprintln(w, "usage: access-engine <command> [options]")
|
||||
fmt.Fprintln(w, "commands: version, validate, load-registry, test-policy, check, batch-check, list-allowed, explain, serve, serve-readback")
|
||||
}
|
||||
|
||||
type keyValueFlags []string
|
||||
|
||||
func (f *keyValueFlags) String() string {
|
||||
return strings.Join(*f, ",")
|
||||
}
|
||||
|
||||
func (f *keyValueFlags) Set(value string) error {
|
||||
if !strings.Contains(value, "=") {
|
||||
return fmt.Errorf("filter must be key=value")
|
||||
}
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f keyValueFlags) Map() map[string]any {
|
||||
out := make(map[string]any, len(f))
|
||||
for _, item := range f {
|
||||
key, value, _ := strings.Cut(item, "=")
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (f keyValueFlags) StringMap() map[string]string {
|
||||
out := make(map[string]string, len(f))
|
||||
for _, item := range f {
|
||||
key, value, _ := strings.Cut(item, "=")
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
# Authenticated Go decision client
|
||||
|
||||
`pkg/decisionpep` is the producer-owned consumer of the normal signed Check
|
||||
contract. It sends one current request with a fresh nonce, validates the unchanged
|
||||
producer signature and exact request/policy/registry/caller/lifetime bindings, and
|
||||
returns only a verified ALLOW without unimplemented obligations. It renders no
|
||||
policy and grants no protected effect itself. It requires the explicit
|
||||
`lossless-json-v1` wire profile and signed `standalone/lossless-json-v1` provenance;
|
||||
legacy callers keep their original numeric projection. Purpose-bearing readback
|
||||
and the separate trusted task-execution profile are not accepted by this client.
|
||||
|
||||
The standalone Go 1.24 slice is generated from the same root source with
|
||||
`make decisionpep-export`. `make decisionpep-check` and the ordinary root Go tests
|
||||
refuse export drift. The export contains exact API/signature source, one client,
|
||||
its tests, license and a synthetic-fixture signer. It contains no signer key,
|
||||
credential, OPA engine, policy evaluator or deployable service. Outer release
|
||||
provenance pins the actual producer commit and complete export hashes; the
|
||||
manifest's older API/signature baseline identifies those unchanged contract bytes.
|
||||
|
||||
Consumers vendor the generated directory and retain its original module/import
|
||||
identity through their dependency lock. Independently admitted configuration must
|
||||
supply the HTTPS endpoint, CA, PDP public keys, policy/registry digests and caller
|
||||
identity, with only a path to the private rotating caller credential. There is no
|
||||
usable production admission or default trust in this source example. Do not
|
||||
bootstrap trust from a response, environment proxy, token contents or discovered
|
||||
key. Redirects, missing trust and unavailable/expired/unsigned/downgraded decisions
|
||||
refuse. Caller credentials are read per Check; consumers must also reload their
|
||||
admission under the owner's revocation and rotation contract.
|
||||
|
||||
The Forgejo example keeps the three original groups in PDP policy. Its application
|
||||
resource tenant and issuer are registry-owned. Verified runtime identity and fresh
|
||||
UserInfo facts are supplied in request context only by the admitted Forgejo caller;
|
||||
they are not fictional static subject attributes. The actual Forgejo consumer
|
||||
independently validates issuer JWT signature, algorithm, type, issuer, audience,
|
||||
authorized party and lifetime before consulting this PDP. The example registry and
|
||||
keys used in tests are synthetic. A login callback decision covers that callback;
|
||||
it does not establish later HTTP/API/Git/SSH, operation/inverse or session
|
||||
revocation acceptance. Native application admission and complete coverage remain
|
||||
CUST-WP-0080 / NK-WP-0048-T43 / RAPPS-WP-0016-T09 work.
|
||||
|
|
@ -0,0 +1,196 @@
|
|||
---
|
||||
id: forgejo.application-access
|
||||
name: Forgejo authenticated application access
|
||||
namespace: forgejo:application
|
||||
version: v1
|
||||
status: draft
|
||||
package: flexauth.forgejo.application
|
||||
allow_ttl: 10s
|
||||
actions: [application.access]
|
||||
owner: railiance-apps
|
||||
caring:
|
||||
profile: caring-0.4.0-rc2
|
||||
enforce: false
|
||||
---
|
||||
|
||||
This source policy enforces the original three-group any-of in the sole PDP.
|
||||
The registry identifies the application tenant and admitted issuer. Fresh identity
|
||||
and UserInfo facts arrive only in request context from the admitted Forgejo caller,
|
||||
which verifies issuer JOSE and current UserInfo before this request. They are not
|
||||
static subject registry attributes. This policy requires aal2 assurance.
|
||||
The PEP independently verifies the ID token and supplies fresh UserInfo groups;
|
||||
the authenticated workload caller may represent only the Forgejo system. A
|
||||
decision authorizes one login callback, never a later HTTP/Git/SSH/API operation.
|
||||
The accompanying registry is synthetic test data, not an estate admission.
|
||||
|
||||
```rego
|
||||
import rego.v1
|
||||
|
||||
default decision := {"effect": "deny", "reason": "application_access_refused"}
|
||||
|
||||
original_groups := {"forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"}
|
||||
|
||||
decision := {"effect": "allow", "reason": "current_authenticated_application_access"} if {
|
||||
input.action == "application.access"
|
||||
object.get(input, "purpose", "") == ""
|
||||
input.resource.id == "application:forgejo"
|
||||
input.resource.type == "application"
|
||||
input.resource.system == "forgejo"
|
||||
input.tenant == input.resource.tenant
|
||||
input.tenant == input.resource.attributes.tenant
|
||||
input.subject.tenant == input.tenant
|
||||
input.context.identity_tenant == input.tenant
|
||||
input.subject.id == input.context.identity_subject
|
||||
input.subject.type == input.context.identity_principal_type
|
||||
input.subject.type == "human"
|
||||
input.context.identity_issuer == input.resource.attributes.identity_issuer
|
||||
input.context.identity_assurance == "aal2"
|
||||
is_array(input.context.required_groups_any_of)
|
||||
count(input.context.required_groups_any_of) == 3
|
||||
{g | g := input.context.required_groups_any_of[_]} == original_groups
|
||||
is_array(input.context.current_userinfo_groups)
|
||||
every value in input.context.current_userinfo_groups { is_string(value) }
|
||||
some group in input.context.current_userinfo_groups
|
||||
group in original_groups
|
||||
is_string(input.context.decisionpep_request_nonce)
|
||||
count(input.context.decisionpep_request_nonce) == 64
|
||||
}
|
||||
```
|
||||
|
||||
```rego test
|
||||
package flexauth.forgejo.application_test
|
||||
import rego.v1
|
||||
import data.flexauth.forgejo.application
|
||||
|
||||
valid_request := {
|
||||
"tenant": "tenant:synthetic",
|
||||
"subject": {
|
||||
"id": "user:synthetic",
|
||||
"type": "human",
|
||||
"tenant": "tenant:synthetic"
|
||||
},
|
||||
"action": "application.access",
|
||||
"resource": {
|
||||
"id": "application:forgejo",
|
||||
"type": "application",
|
||||
"system": "forgejo",
|
||||
"tenant": "tenant:synthetic",
|
||||
"attributes": {
|
||||
"tenant": "tenant:synthetic",
|
||||
"identity_issuer": "https://issuer.invalid"
|
||||
}
|
||||
},
|
||||
"context": {
|
||||
"identity_tenant": "tenant:synthetic",
|
||||
"identity_subject": "user:synthetic",
|
||||
"identity_principal_type": "human",
|
||||
"identity_issuer": "https://issuer.invalid",
|
||||
"identity_assurance": "aal2",
|
||||
"current_userinfo_groups": [
|
||||
"forge-admins"
|
||||
],
|
||||
"required_groups_any_of": [
|
||||
"forge-admins",
|
||||
"forge-coulomb-owners",
|
||||
"forge-coulomb-readers"
|
||||
],
|
||||
"decisionpep_request_nonce": "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
}
|
||||
|
||||
test_original_groups_allow if {
|
||||
every group in ["forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"] {
|
||||
application.decision.effect == "allow" with input as object.union(valid_request, {"context": object.union(valid_request.context, {"current_userinfo_groups": [group]})})
|
||||
}
|
||||
}
|
||||
|
||||
test_outsider_denied if {
|
||||
application.decision.effect == "deny" with input as object.union(valid_request, {"context": object.union(valid_request.context, {"current_userinfo_groups": ["outsider"]})})
|
||||
}
|
||||
|
||||
test_missing_identity_denied if {
|
||||
application.decision.effect == "deny" with input as object.union(object.remove(valid_request, ["context"]), {"context": object.remove(valid_request.context, ["identity_issuer"])})
|
||||
}
|
||||
|
||||
test_low_assurance_denied if {
|
||||
application.decision.effect == "deny" with input as object.union(valid_request, {"context": object.union(valid_request.context, {"identity_assurance": "aal1"})})
|
||||
}
|
||||
|
||||
test_changed_group_contract_denied if {
|
||||
application.decision.effect == "deny" with input as object.union(valid_request, {"context": object.union(valid_request.context, {"required_groups_any_of": ["outsider"]})})
|
||||
}
|
||||
```
|
||||
|
||||
```yaml fixture
|
||||
[
|
||||
{
|
||||
"id": "allowed-original-group",
|
||||
"request": {
|
||||
"tenant": "tenant:synthetic",
|
||||
"subject": {
|
||||
"id": "user:synthetic",
|
||||
"type": "human",
|
||||
"tenant": "tenant:synthetic"
|
||||
},
|
||||
"action": "application.access",
|
||||
"resource": {
|
||||
"id": "application:forgejo",
|
||||
"type": "application",
|
||||
"system": "forgejo",
|
||||
"tenant": "tenant:synthetic",
|
||||
"attributes": {
|
||||
"tenant": "tenant:synthetic",
|
||||
"identity_issuer": "https://issuer.invalid"
|
||||
}
|
||||
},
|
||||
"context": {
|
||||
"identity_tenant": "tenant:synthetic",
|
||||
"identity_subject": "user:synthetic",
|
||||
"identity_principal_type": "human",
|
||||
"identity_issuer": "https://issuer.invalid",
|
||||
"identity_assurance": "aal2",
|
||||
"current_userinfo_groups": [
|
||||
"forge-admins"
|
||||
],
|
||||
"required_groups_any_of": [
|
||||
"forge-admins",
|
||||
"forge-coulomb-owners",
|
||||
"forge-coulomb-readers"
|
||||
],
|
||||
"decisionpep_request_nonce": "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
"expect": {
|
||||
"effect": "allow",
|
||||
"reason": "current_authenticated_application_access"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "missing-identity-context",
|
||||
"request": {
|
||||
"tenant": "tenant:synthetic",
|
||||
"subject": {
|
||||
"id": "user:synthetic",
|
||||
"type": "human",
|
||||
"tenant": "tenant:synthetic"
|
||||
},
|
||||
"action": "application.access",
|
||||
"resource": {
|
||||
"id": "application:forgejo",
|
||||
"type": "application",
|
||||
"system": "forgejo",
|
||||
"tenant": "tenant:synthetic",
|
||||
"attributes": {
|
||||
"tenant": "tenant:synthetic",
|
||||
"identity_issuer": "https://issuer.invalid"
|
||||
}
|
||||
},
|
||||
"context": {}
|
||||
},
|
||||
"expect": {
|
||||
"effect": "deny",
|
||||
"reason": "application_access_refused"
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"systems": [
|
||||
{
|
||||
"id": "forgejo",
|
||||
"name": "Synthetic test only",
|
||||
"resource_types": [
|
||||
{
|
||||
"name": "application"
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"name": "application.access"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjects": [],
|
||||
"resource_manifests": [
|
||||
{
|
||||
"id": "forgejo.synthetic.resources",
|
||||
"system": "forgejo",
|
||||
"resources": [
|
||||
{
|
||||
"id": "application:forgejo",
|
||||
"type": "application",
|
||||
"attributes": {
|
||||
"identity_issuer": "https://issuer.invalid",
|
||||
"tenant": "tenant:synthetic"
|
||||
}
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
"application.access"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"systems": [
|
||||
{
|
||||
"id": "forgejo",
|
||||
"name": "Synthetic test only",
|
||||
"resource_types": [
|
||||
{
|
||||
"name": "application"
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"name": "application.access"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjects": [],
|
||||
"resource_manifests": [
|
||||
{
|
||||
"id": "forgejo.synthetic.resources",
|
||||
"system": "forgejo",
|
||||
"resources": [
|
||||
{
|
||||
"id": "application:forgejo",
|
||||
"type": "application",
|
||||
"attributes": {
|
||||
"identity_issuer": "https://issuer.invalid",
|
||||
"tenant": "tenant:synthetic"
|
||||
}
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
"application.access"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,729 @@
|
|||
package decision
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/callerauth"
|
||||
"github.com/netkingdom/access-engine/internal/policy"
|
||||
"github.com/netkingdom/access-engine/internal/registry"
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/internal/taskexecution"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// Engine evaluates deterministic standalone authorization checks against a
|
||||
// local registry and one validated policy package.
|
||||
type Engine struct {
|
||||
store *registry.Store
|
||||
policy *policy.Package
|
||||
mu sync.RWMutex
|
||||
history map[string]api.DecisionEnvelope
|
||||
log DecisionRecorder
|
||||
clock func() time.Time
|
||||
signingKey ed25519.PrivateKey
|
||||
signingKID string
|
||||
}
|
||||
|
||||
// DecisionRecorder persists decision envelopes.
|
||||
type DecisionRecorder interface {
|
||||
Append(api.DecisionEnvelope) error
|
||||
}
|
||||
|
||||
// BatchRecorder commits several decisions in one durable write.
|
||||
type BatchRecorder interface {
|
||||
AppendBatch([]api.DecisionEnvelope) error
|
||||
}
|
||||
|
||||
// ErrRecordNotCommitted means a decision was withheld because its required
|
||||
// record did not commit (GH-DEC-2026-024). The service answers 503; this is
|
||||
// unavailability, never a substitute authorization verdict.
|
||||
var ErrRecordNotCommitted = errors.New("decision withheld: record not committed")
|
||||
|
||||
// ListAllowedRequest describes a deterministic list_allowed call.
|
||||
type ListAllowedRequest struct {
|
||||
Subject api.SubjectRef `json:"subject"`
|
||||
Action string `json:"action"`
|
||||
System string `json:"system,omitempty"`
|
||||
ResourceType string `json:"resource_type,omitempty"`
|
||||
Filters map[string]any `json:"filters,omitempty"`
|
||||
Context map[string]any `json:"context,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty"`
|
||||
}
|
||||
|
||||
// Explanation is a compact explanation view over a recorded decision.
|
||||
type Explanation struct {
|
||||
DecisionID string `json:"decision_id"`
|
||||
Effect api.DecisionEffect `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Summary string `json:"summary"`
|
||||
Subject api.SubjectRef `json:"subject"`
|
||||
Resource api.ResourceRef `json:"resource"`
|
||||
PolicyPackage string `json:"policy_package,omitempty"`
|
||||
PolicyVersion string `json:"policy_version,omitempty"`
|
||||
MatchedRule string `json:"matched_rule,omitempty"`
|
||||
Diagnostics map[string]any `json:"diagnostics,omitempty"`
|
||||
Caring *api.CaringDecisionMetadata `json:"caring,omitempty"`
|
||||
}
|
||||
|
||||
// NewEngine creates a standalone decision engine.
|
||||
func NewEngine(store *registry.Store, policyPackage *policy.Package) (*Engine, error) {
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("registry store is required")
|
||||
}
|
||||
if policyPackage == nil {
|
||||
return nil, fmt.Errorf("policy package is required")
|
||||
}
|
||||
if !policyPackage.Valid {
|
||||
return nil, fmt.Errorf("policy package %q is not valid", policyPackage.Metadata.ID)
|
||||
}
|
||||
return &Engine{
|
||||
store: store,
|
||||
policy: policyPackage,
|
||||
history: make(map[string]api.DecisionEnvelope),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetEnvelopeSigningKey installs an owner-custodied key before serving requests.
|
||||
// The key is copied so caller mutation cannot change the admitted signer.
|
||||
func (e *Engine) SetEnvelopeSigningKey(key ed25519.PrivateKey, kid string) error {
|
||||
if len(key) != ed25519.PrivateKeySize || strings.TrimSpace(kid) == "" {
|
||||
return fmt.Errorf("valid Ed25519 private key and kid are required")
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.signingKey = append(ed25519.PrivateKey(nil), key...)
|
||||
e.signingKID = kid
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDecisionLog attaches a local decision recorder to the engine.
|
||||
func (e *Engine) SetDecisionLog(log DecisionRecorder) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.log = log
|
||||
}
|
||||
|
||||
// SetClock overrides the engine clock. Tests use this to pin allow lifetimes.
|
||||
func (e *Engine) SetClock(clock func() time.Time) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.clock = clock
|
||||
}
|
||||
|
||||
func (e *Engine) now() time.Time {
|
||||
e.mu.RLock()
|
||||
clock := e.clock
|
||||
e.mu.RUnlock()
|
||||
if clock != nil {
|
||||
return clock().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
// decide evaluates one request without recording it.
|
||||
func (e *Engine) decide(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
normalized, facts := e.normalizeRequest(request)
|
||||
|
||||
expectation, err := e.policy.Evaluate(ctx, normalized)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
|
||||
envelope := e.envelope(ctx, normalized, request, expectation, facts)
|
||||
e.mu.RLock()
|
||||
key, kid := e.signingKey, e.signingKID
|
||||
e.mu.RUnlock()
|
||||
if len(key) != 0 {
|
||||
if err := sign.Sign(&envelope, key, kid); err != nil {
|
||||
return api.DecisionEnvelope{}, fmt.Errorf("decision signing failed: %w", err)
|
||||
}
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// IsServicePilot selects the existing exact source package, never a request flag.
|
||||
func (e *Engine) IsServicePilot() bool {
|
||||
return e.policy.Metadata.ID == taskexecution.ServicePilotPackageID && e.policy.Metadata.Version == taskexecution.ServicePilotPackageVersion
|
||||
}
|
||||
func (e *Engine) IsTrustedServicePilot() bool {
|
||||
return e.policy.Metadata.ID == taskexecution.ServicePilotPackageID && e.policy.Metadata.Version == taskexecution.TrustedServicePilotPackageVersion
|
||||
}
|
||||
func (e *Engine) IsTaskPin() bool { return e.IsServicePilot() || e.IsTrustedServicePilot() }
|
||||
|
||||
// ErrServicePilotUnavailable withholds any result that is not this B1 slice's
|
||||
// signed DENY. Provider joins and executable eligibility remain unimplemented.
|
||||
var ErrServicePilotUnavailable = errors.New("service pilot source path unavailable")
|
||||
|
||||
// CheckServicePilot records only a signed DENY after authenticating the exact
|
||||
// immutable service input. It does not validate Approval facts or grant an act.
|
||||
func (e *Engine) CheckServicePilot(ctx context.Context, input taskexecution.ServiceInput) (api.DecisionEnvelope, error) {
|
||||
if !e.IsServicePilot() {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
request, err := input.RequestAt(e.now())
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
envelope, err := e.decide(callerauth.WithRecord(ctx, input.Caller()), request)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
if envelope.Effect != api.DecisionEffectDeny || envelope.Signature == nil || envelope.Signature.Mode != api.EnvelopeSignatureSigned {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
if err := e.recordDecisions([]api.DecisionEnvelope{envelope}); err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// Check evaluates one subject/action/resource request. The decision is
|
||||
// released only after its required record commits (GH-DEC-2026-024).
|
||||
func (e *Engine) Check(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return api.DecisionEnvelope{}, ErrServicePilotUnavailable
|
||||
}
|
||||
decision, err := e.decide(ctx, request)
|
||||
if err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
if err := e.recordDecisions([]api.DecisionEnvelope{decision}); err != nil {
|
||||
return api.DecisionEnvelope{}, err
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// BatchCheck evaluates one subject/action/context tuple against resources in
|
||||
// request order, and commits the whole batch in one durable write.
|
||||
func (e *Engine) BatchCheck(ctx context.Context, request api.BatchCheckRequest) ([]api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return nil, ErrServicePilotUnavailable
|
||||
}
|
||||
decisions := make([]api.DecisionEnvelope, 0, len(request.Resources))
|
||||
for _, resource := range request.Resources {
|
||||
decision, err := e.decide(ctx, api.CheckRequest{
|
||||
ID: request.ID,
|
||||
Tenant: request.Tenant,
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: resource,
|
||||
Context: request.Context,
|
||||
PolicyVersion: request.PolicyVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := e.recordDecisions(decisions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decisions, nil
|
||||
}
|
||||
|
||||
// ListAllowed evaluates candidate resources and returns only allow decisions.
|
||||
func (e *Engine) ListAllowed(ctx context.Context, request ListAllowedRequest) ([]api.DecisionEnvelope, error) {
|
||||
if e.IsTaskPin() || request.Action == "execute-ccr" {
|
||||
return nil, ErrServicePilotUnavailable
|
||||
}
|
||||
candidates := e.store.ResourceRefs(request.System, request.ResourceType)
|
||||
decisions := make([]api.DecisionEnvelope, 0, len(candidates))
|
||||
for _, resource := range candidates {
|
||||
if !resourceMatchesFilters(resource, request.Filters) {
|
||||
continue
|
||||
}
|
||||
decision, err := e.decide(ctx, api.CheckRequest{
|
||||
Subject: request.Subject,
|
||||
Action: request.Action,
|
||||
Resource: resource,
|
||||
Context: request.Context,
|
||||
PolicyVersion: request.PolicyVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
if err := e.recordDecisions(decisions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allowed := make([]api.DecisionEnvelope, 0, len(decisions))
|
||||
for _, decision := range decisions {
|
||||
if decision.Effect == api.DecisionEffectAllow {
|
||||
allowed = append(allowed, decision)
|
||||
}
|
||||
}
|
||||
return allowed, nil
|
||||
}
|
||||
|
||||
// Explain returns a CARING-aware explanation for a decision recorded by this
|
||||
// engine instance. P2.6 replaces this in-memory history with the local log.
|
||||
func (e *Engine) Explain(decisionID string) (Explanation, error) {
|
||||
e.mu.RLock()
|
||||
decision, ok := e.history[decisionID]
|
||||
e.mu.RUnlock()
|
||||
if !ok {
|
||||
return Explanation{}, fmt.Errorf("decision %q not found", decisionID)
|
||||
}
|
||||
|
||||
return ExplainEnvelope(decision), nil
|
||||
}
|
||||
|
||||
// ExplainEnvelope returns the same explanation shape for an already-loaded
|
||||
// decision envelope.
|
||||
func ExplainEnvelope(decision api.DecisionEnvelope) Explanation {
|
||||
return Explanation{
|
||||
DecisionID: decision.ID,
|
||||
Effect: decision.Effect,
|
||||
Reason: decision.Reason,
|
||||
Summary: explanationSummary(decision),
|
||||
Subject: decision.Subject,
|
||||
Resource: decision.Resource,
|
||||
PolicyPackage: decision.Provenance.PolicyPackage,
|
||||
PolicyVersion: decision.Provenance.PolicyVersion,
|
||||
MatchedRule: decision.MatchedRule,
|
||||
Diagnostics: decision.Diagnostics,
|
||||
Caring: decision.Caring,
|
||||
}
|
||||
}
|
||||
|
||||
type registryFacts struct {
|
||||
subjectFound bool
|
||||
resourceFound bool
|
||||
subject api.Subject
|
||||
resource api.Resource
|
||||
matchedRelationship string
|
||||
descriptor *api.CaringAccessDescriptor
|
||||
// overriddenByRegistry names request attribute keys whose caller-supplied
|
||||
// value was displaced by a registry fact. Empty on an honest request; a
|
||||
// non-empty list means the caller asserted something the registry contradicts,
|
||||
// which is worth seeing even though the registry won (FLEX-DEC-2026-012).
|
||||
overriddenByRegistry []string
|
||||
}
|
||||
|
||||
func (e *Engine) normalizeRequest(request api.CheckRequest) (api.CheckRequest, registryFacts) {
|
||||
normalized := request
|
||||
facts := registryFacts{}
|
||||
|
||||
overridden := []string{}
|
||||
|
||||
if normalized.Tenant != "" {
|
||||
if normalized.Subject.Tenant == "" {
|
||||
normalized.Subject.Tenant = normalized.Tenant
|
||||
}
|
||||
if normalized.Resource.Tenant == "" {
|
||||
normalized.Resource.Tenant = normalized.Tenant
|
||||
}
|
||||
}
|
||||
|
||||
if subject, ok := e.store.Subject(request.Subject.ID); ok {
|
||||
facts.subjectFound = true
|
||||
facts.subject = subject
|
||||
normalized.Subject = enrichSubjectRef(request.Subject, subject, &overridden)
|
||||
}
|
||||
|
||||
if resource, ok := e.store.Resource(request.Resource.System, request.Resource.ID); ok {
|
||||
facts.resourceFound = true
|
||||
facts.resource = resource
|
||||
normalized.Resource = enrichResourceRef(request.Resource, resource, &overridden)
|
||||
}
|
||||
|
||||
if normalized.CaringContext != nil {
|
||||
descriptor := *normalized.CaringContext
|
||||
facts.descriptor = &descriptor
|
||||
facts.overriddenByRegistry = overridden
|
||||
return normalized, facts
|
||||
}
|
||||
|
||||
facts.overriddenByRegistry = overridden
|
||||
|
||||
if descriptor, relationshipID := e.matchCaringDescriptor(normalized, facts); descriptor != nil {
|
||||
facts.descriptor = descriptor
|
||||
facts.matchedRelationship = relationshipID
|
||||
normalized.CaringContext = descriptor
|
||||
} else if facts.resourceFound && facts.resource.Caring != nil {
|
||||
descriptor := *facts.resource.Caring
|
||||
facts.descriptor = &descriptor
|
||||
normalized.CaringContext = &descriptor
|
||||
}
|
||||
|
||||
return normalized, facts
|
||||
}
|
||||
|
||||
func (e *Engine) matchCaringDescriptor(request api.CheckRequest, facts registryFacts) (*api.CaringAccessDescriptor, string) {
|
||||
candidates := []string{request.Subject.ID}
|
||||
if facts.subjectFound {
|
||||
candidates = append(candidates, facts.subject.Groups...)
|
||||
}
|
||||
|
||||
for _, relationship := range e.store.RelationshipsForObject(request.Resource.ID) {
|
||||
if relationship.Caring == nil {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(candidates, relationship.Subject) {
|
||||
continue
|
||||
}
|
||||
if relationship.System != "" && relationship.System != request.Resource.System {
|
||||
continue
|
||||
}
|
||||
if relationship.Tenant != "" && request.Resource.Tenant != "" && relationship.Tenant != request.Resource.Tenant {
|
||||
continue
|
||||
}
|
||||
descriptor := *relationship.Caring
|
||||
return &descriptor, relationship.ID
|
||||
}
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
// enrichSubjectRef overlays registry facts onto the subject the caller sent.
|
||||
//
|
||||
// Registry facts WIN. A value in the registry is an authority statement; the
|
||||
// same key on the request is the caller's proposal about itself. Letting the
|
||||
// proposal survive made a registry ceiling advisory — see FLEX-DEC-2026-012,
|
||||
// where a caller supplying resource.attributes.allowed_subjects authorized a
|
||||
// subject the registry did not know.
|
||||
//
|
||||
// Keys the registry does not define still pass through from the request. That
|
||||
// residual is stated in docs/request-enrichment.md rather than fixed here: a
|
||||
// policy reading a key its manifest omits is consuming caller input, and the
|
||||
// structural fix is separating the two namespaces (FLEX-WP-0025).
|
||||
func enrichSubjectRef(ref api.SubjectRef, subject api.Subject, overridden *[]string) api.SubjectRef {
|
||||
out := ref
|
||||
// subject.Type is deliberately NOT overwritten, unlike every other registry
|
||||
// fact here. The registry's Type is CARING vocabulary (Human, Agent,
|
||||
// Automation, Service); the request's is the protected system's actor
|
||||
// vocabulary (service, adm, agt, atm). They are two different fields sharing
|
||||
// a name, and substituting one for the other is translation rather than
|
||||
// identity — the error GH-DEC-2026-008 ruled against. Making the registry win
|
||||
// here denied every secrets-engine allow, because "Service" is not "service".
|
||||
//
|
||||
// The residual is that a caller can still assert its own subject.type and
|
||||
// packages branch on it. That is not fixable by overwriting from a different
|
||||
// vocabulary; it needs the two fields separated. FLEX-WP-0025.
|
||||
if out.Type == "" {
|
||||
out.Type = subject.Type
|
||||
}
|
||||
if subject.Tenant != "" {
|
||||
out.Tenant = subject.Tenant
|
||||
}
|
||||
out.Attributes = copyMap(out.Attributes)
|
||||
setAuthoritative(out.Attributes, "display_name", subject.DisplayName, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "organization_relation", subject.OrganizationRelation, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "roles", subject.Roles, "subject", overridden)
|
||||
setAuthoritative(out.Attributes, "groups", subject.Groups, "subject", overridden)
|
||||
setAuthoritatives(out.Attributes, subject.Claims, "subject", overridden)
|
||||
setAuthoritatives(out.Attributes, subject.Metadata, "subject", overridden)
|
||||
return out
|
||||
}
|
||||
|
||||
// enrichResourceRef overlays registry facts onto the resource the caller sent.
|
||||
// Registry facts win, for the reason given on enrichSubjectRef: ops-warden's
|
||||
// max_ttl_hours, allowed_subjects, and allowed_principals are ceilings and
|
||||
// allowlists, and a ceiling a caller can raise is not a ceiling.
|
||||
func enrichResourceRef(ref api.ResourceRef, resource api.Resource, overridden *[]string) api.ResourceRef {
|
||||
out := ref
|
||||
if resource.Type != "" {
|
||||
out.Type = resource.Type
|
||||
}
|
||||
out.Attributes = copyMap(out.Attributes)
|
||||
setAuthoritative(out.Attributes, "path", resource.Path, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "parent", resource.Parent, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "labels", resource.Labels, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "trust_zone", resource.TrustZone, "resource", overridden)
|
||||
setAuthoritative(out.Attributes, "owner", resource.Owner, "resource", overridden)
|
||||
setAuthoritatives(out.Attributes, resource.Attributes, "resource", overridden)
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *Engine) envelope(ctx context.Context, request, submitted api.CheckRequest, expectation api.DecisionExpectation, facts registryFacts) api.DecisionEnvelope {
|
||||
envelope := api.DecisionEnvelope{
|
||||
RequestID: request.ID,
|
||||
Effect: expectation.Effect,
|
||||
Reason: expectation.Reason,
|
||||
MatchedPolicyVersion: e.policy.Metadata.Version,
|
||||
MatchedRule: expectation.Reason,
|
||||
Resource: request.Resource,
|
||||
Subject: request.Subject,
|
||||
Binding: api.NewDecisionBindingFor(request, submitted),
|
||||
Obligations: expectation.Obligations,
|
||||
Diagnostics: map[string]any{
|
||||
"action": request.Action,
|
||||
"policy_package": e.policy.Metadata.ID,
|
||||
"policy_status": e.policy.Metadata.Status,
|
||||
"registry_subject": facts.subjectFound,
|
||||
"registry_resource": facts.resourceFound,
|
||||
"matched_relationship": facts.matchedRelationship,
|
||||
"registry_overrode": facts.overriddenByRegistry,
|
||||
},
|
||||
Provenance: api.DecisionProvenance{
|
||||
Evaluator: "flex-auth/local",
|
||||
Mode: envelopeMode(ctx),
|
||||
PolicyPackage: e.policy.Metadata.ID,
|
||||
PolicyVersion: e.policy.Metadata.Version,
|
||||
PolicyPackageDigest: e.policy.Digest(),
|
||||
RegistrySnapshotDigest: e.store.Digest(),
|
||||
Caller: callerProvenance(ctx),
|
||||
},
|
||||
Caring: e.caringDecisionMetadata(facts.descriptor, expectation.ConformanceFindings),
|
||||
}
|
||||
api.CompleteDecision(&envelope, request, api.DecisionCompletion{
|
||||
AllowTTL: e.policy.Metadata.AllowTTL,
|
||||
Now: e.now(),
|
||||
})
|
||||
envelope.ID = decisionID(e.policy.Metadata, request, envelope)
|
||||
if envelope.Signature == nil {
|
||||
envelope.Signature = api.UnsignedEnvelopeSignature()
|
||||
}
|
||||
return envelope
|
||||
}
|
||||
|
||||
func callerProvenance(ctx context.Context) *api.CallerProvenance {
|
||||
record, ok := callerauth.RecordFromContext(ctx)
|
||||
if !ok {
|
||||
record = callerauth.Record{Mode: callerauth.ModeDisabled}
|
||||
}
|
||||
out := &api.CallerProvenance{Mode: string(record.Mode)}
|
||||
if record.Principal != "" {
|
||||
out.Principal = record.Principal
|
||||
out.Audience = record.Audience
|
||||
if !record.NotAfter.IsZero() {
|
||||
out.NotAfter = record.NotAfter.UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// recordDecisions releases no effect until its required record commits.
|
||||
// GH-DEC-2026-024 refuses the former restrictive-effect failure exception.
|
||||
// Failed decisions must not enter Explain's history as if they were released.
|
||||
func (e *Engine) recordDecisions(decisions []api.DecisionEnvelope) error {
|
||||
e.mu.RLock()
|
||||
log := e.log
|
||||
e.mu.RUnlock()
|
||||
if log != nil && len(decisions) != 0 {
|
||||
if err := appendAll(log, decisions); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrRecordNotCommitted, err)
|
||||
}
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, decision := range decisions {
|
||||
e.history[decision.ID] = decision
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func appendAll(log DecisionRecorder, decisions []api.DecisionEnvelope) error {
|
||||
if batch, ok := log.(BatchRecorder); ok {
|
||||
return batch.AppendBatch(decisions)
|
||||
}
|
||||
for _, decision := range decisions {
|
||||
if err := log.Append(decision); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) caringDecisionMetadata(descriptor *api.CaringAccessDescriptor, findings []api.CaringConformanceFinding) *api.CaringDecisionMetadata {
|
||||
profile := e.policy.Metadata.Caring.Profile
|
||||
if descriptor != nil && descriptor.Profile != "" {
|
||||
profile = descriptor.Profile
|
||||
}
|
||||
|
||||
metadata := &api.CaringDecisionMetadata{
|
||||
Profile: profile,
|
||||
ConformanceFindings: append([]api.CaringConformanceFinding(nil), findings...),
|
||||
}
|
||||
if descriptor == nil {
|
||||
metadata.ConformanceFindings = append(metadata.ConformanceFindings, api.CaringConformanceFinding{
|
||||
Code: "CARING-DESCRIPTOR-MISSING",
|
||||
Severity: "warning",
|
||||
Message: "no CARING descriptor matched the request",
|
||||
Fields: []string{"caring_context"},
|
||||
})
|
||||
return metadata
|
||||
}
|
||||
|
||||
descriptorCopy := *descriptor
|
||||
metadata.Descriptor = &descriptorCopy
|
||||
metadata.RestrictionsEvaluated = append([]api.Restriction(nil), descriptor.Restrictions...)
|
||||
metadata.ExposureModes = append([]api.ExposureMode(nil), descriptor.ExposureModes...)
|
||||
metadata.DerivedCapabilities = append([]api.CaringDerivedCapability(nil), descriptor.DerivedCapabilities...)
|
||||
return metadata
|
||||
}
|
||||
|
||||
func decisionID(metadata api.PolicyPackageMetadata, request api.CheckRequest, envelope api.DecisionEnvelope) string {
|
||||
data, _ := json.Marshal(struct {
|
||||
PolicyID string `json:"policy_id"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Request api.CheckRequest `json:"request"`
|
||||
Effect api.DecisionEffect `json:"effect"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}{
|
||||
PolicyID: metadata.ID,
|
||||
PolicyVersion: metadata.Version,
|
||||
Request: request,
|
||||
Effect: envelope.Effect,
|
||||
Reason: envelope.Reason,
|
||||
})
|
||||
sum := sha256.Sum256(data)
|
||||
return "decision:" + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
func copyMap(in map[string]any) map[string]any {
|
||||
out := make(map[string]any, len(in))
|
||||
for key, value := range in {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// setAuthoritative writes a registry fact over whatever the request carried for
|
||||
// that key, and records the key when a caller value was displaced so the
|
||||
// override is visible in diagnostics rather than silent.
|
||||
func setAuthoritative(target map[string]any, key string, value any, scope string, overridden *[]string) {
|
||||
if isEmptyAttribute(value) {
|
||||
return
|
||||
}
|
||||
if existing, exists := target[key]; exists && overridden != nil && !equalAttribute(existing, value) {
|
||||
*overridden = append(*overridden, scope+"."+key)
|
||||
}
|
||||
target[key] = value
|
||||
}
|
||||
|
||||
func setAuthoritatives(target map[string]any, attrs map[string]any, scope string, overridden *[]string) {
|
||||
for _, key := range sortedKeys(attrs) {
|
||||
setAuthoritative(target, key, attrs[key], scope, overridden)
|
||||
}
|
||||
}
|
||||
|
||||
func equalAttribute(a, b any) bool {
|
||||
left, errLeft := json.Marshal(a)
|
||||
right, errRight := json.Marshal(b)
|
||||
if errLeft != nil || errRight != nil {
|
||||
return false
|
||||
}
|
||||
return bytes.Equal(left, right)
|
||||
}
|
||||
|
||||
func sortedKeys(attrs map[string]any) []string {
|
||||
keys := make([]string, 0, len(attrs))
|
||||
for key := range attrs {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
func addAttributes(target map[string]any, attrs map[string]any) {
|
||||
for key, value := range attrs {
|
||||
addAttribute(target, key, value)
|
||||
}
|
||||
}
|
||||
|
||||
func addAttribute(target map[string]any, key string, value any) {
|
||||
if isEmptyAttribute(value) {
|
||||
return
|
||||
}
|
||||
if _, exists := target[key]; !exists {
|
||||
target[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
func resourceMatchesFilters(resource api.ResourceRef, filters map[string]any) bool {
|
||||
for key, want := range filters {
|
||||
var got any
|
||||
switch key {
|
||||
case "id":
|
||||
got = resource.ID
|
||||
case "type", "resource_type":
|
||||
got = resource.Type
|
||||
case "system":
|
||||
got = resource.System
|
||||
case "tenant":
|
||||
got = resource.Tenant
|
||||
default:
|
||||
got = resource.Attributes[key]
|
||||
}
|
||||
if !valuesEqual(got, want) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func valuesEqual(got, want any) bool {
|
||||
if reflect.DeepEqual(got, want) {
|
||||
return true
|
||||
}
|
||||
return fmt.Sprint(got) == fmt.Sprint(want)
|
||||
}
|
||||
|
||||
func explanationSummary(decision api.DecisionEnvelope) string {
|
||||
action, _ := decision.Diagnostics["action"].(string)
|
||||
actor := decision.Subject.ID
|
||||
capability := action
|
||||
plane := ""
|
||||
if decision.Caring != nil && decision.Caring.Descriptor != nil {
|
||||
descriptor := decision.Caring.Descriptor
|
||||
if descriptor.OrganizationRelation != "" || descriptor.CanonicalRole != "" {
|
||||
actor = strings.TrimSpace(fmt.Sprintf("%s %s", descriptor.OrganizationRelation, descriptor.CanonicalRole))
|
||||
}
|
||||
if len(descriptor.Capabilities) > 0 {
|
||||
capability = string(descriptor.Capabilities[0])
|
||||
}
|
||||
if len(descriptor.Planes) > 0 {
|
||||
plane = string(descriptor.Planes[0]) + " Plane "
|
||||
}
|
||||
}
|
||||
if capability == "" {
|
||||
capability = "access"
|
||||
}
|
||||
|
||||
verb := "may"
|
||||
switch decision.Effect {
|
||||
case api.DecisionEffectDeny:
|
||||
verb = "may not"
|
||||
case api.DecisionEffectRedact:
|
||||
verb = "receives redacted"
|
||||
case api.DecisionEffectAuditOnly:
|
||||
verb = "is audit-only for"
|
||||
case api.DecisionEffectNotApplicable:
|
||||
verb = "has no applicable policy for"
|
||||
}
|
||||
|
||||
reason := decision.Reason
|
||||
if reason == "" {
|
||||
reason = string(decision.Effect)
|
||||
}
|
||||
return fmt.Sprintf("%s %s %s %sresource %s because %s.", actor, verb, capability, plane, decision.Resource.ID, reason)
|
||||
}
|
||||
|
||||
func isEmptyAttribute(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return typed == ""
|
||||
case api.OrganizationRelation:
|
||||
return typed == ""
|
||||
case []api.CanonicalRole:
|
||||
return len(typed) == 0
|
||||
case []string:
|
||||
return len(typed) == 0
|
||||
default:
|
||||
return value == nil
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package decision
|
||||
|
||||
import "context"
|
||||
|
||||
// LosslessJSONProfile is an explicit optional wire decoder profile for the
|
||||
// normal /v1/check handler. Legacy callers retain their original float64
|
||||
// projection. The canonical request and signature algorithms are unchanged.
|
||||
const LosslessJSONProfile = "lossless-json-v1"
|
||||
const losslessStandaloneMode = "standalone/lossless-json-v1"
|
||||
|
||||
type jsonProfileContextKey struct{}
|
||||
|
||||
// WithLosslessJSONProfile is called only by the producer after selecting its
|
||||
// UseNumber decoder. No request/body flag can install this context key. The
|
||||
// signed provenance mode authenticates which decoder produced the decision.
|
||||
func WithLosslessJSONProfile(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, jsonProfileContextKey{}, LosslessJSONProfile)
|
||||
}
|
||||
|
||||
func envelopeMode(ctx context.Context) string {
|
||||
if ctx.Value(jsonProfileContextKey{}) == LosslessJSONProfile {
|
||||
return losslessStandaloneMode
|
||||
}
|
||||
return "standalone"
|
||||
}
|
||||
|
|
@ -0,0 +1,296 @@
|
|||
// Package decisionpep authenticates the producer's decision record for one
|
||||
// current request. It never evaluates policy, caches a verdict, or discovers trust.
|
||||
package decisionpep
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
var ErrRefused = errors.New("authenticated decision refused")
|
||||
|
||||
const nonceKey = "decisionpep_request_nonce"
|
||||
|
||||
const JSONProfile = "lossless-json-v1"
|
||||
const provenanceMode = "standalone/lossless-json-v1"
|
||||
const maxBytes = 2 << 20
|
||||
|
||||
// Admission is public, independently admitted owner configuration. TokenFile is
|
||||
// only a path to a private rotating caller credential, never a literal token.
|
||||
type Admission struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
CAFile string `json:"ca_file"`
|
||||
TokenFile string `json:"token_file"`
|
||||
Keys map[string]string `json:"keys"`
|
||||
Evaluator string `json:"evaluator"`
|
||||
PolicyPackage string `json:"policy_package"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
PolicyDigest string `json:"policy_digest"`
|
||||
RegistryDigest string `json:"registry_digest"`
|
||||
CallerPrincipal string `json:"caller_principal"`
|
||||
CallerAudience string `json:"caller_audience"`
|
||||
MaxTTL string `json:"max_ttl"`
|
||||
MaxClockSkew string `json:"max_clock_skew"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
admission Admission
|
||||
keys map[string]ed25519.PublicKey
|
||||
http *http.Client
|
||||
maxTTL, skew time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// Load reads a current independently admitted file. No trust is bootstrapped
|
||||
// from a PDP response, token contents, discovery endpoint, or environment value.
|
||||
func Load(path string) (*Client, error) {
|
||||
raw, err := readFile(path, false)
|
||||
if err != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
var a Admission
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&a) != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if _, err = d.Token(); err != io.EOF {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
return New(a)
|
||||
}
|
||||
|
||||
func New(a Admission) (*Client, error) {
|
||||
u, err := url.Parse(a.Endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "/v1/check" || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if !filepath.IsAbs(a.CAFile) || !filepath.IsAbs(a.TokenFile) || a.Evaluator == "" || a.PolicyPackage == "" || a.PolicyVersion == "" || a.CallerPrincipal == "" || a.CallerAudience == "" {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if !validDigest(a.PolicyDigest) || !validDigest(a.RegistryDigest) || len(a.Keys) == 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
ttl, err := time.ParseDuration(a.MaxTTL)
|
||||
if err != nil || ttl <= 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
skew, err := time.ParseDuration(a.MaxClockSkew)
|
||||
if err != nil || skew < 0 || skew > ttl {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
ca, err := readFile(a.CAFile, false)
|
||||
if err != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(ca) {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
keys := map[string]ed25519.PublicKey{}
|
||||
for kid, value := range a.Keys {
|
||||
b, e := base64.RawURLEncoding.Strict().DecodeString(value)
|
||||
if e != nil || kid == "" || len(b) != ed25519.PublicKeySize {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
keys[kid] = append(ed25519.PublicKey(nil), b...)
|
||||
}
|
||||
transport := &http.Transport{Proxy: nil, TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}, DisableKeepAlives: true}
|
||||
client := &http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return ErrRefused }}
|
||||
return &Client{admission: a, keys: keys, http: client, maxTTL: ttl, skew: skew, now: time.Now}, nil
|
||||
}
|
||||
|
||||
func validDigest(value string) bool {
|
||||
if !strings.HasPrefix(value, "sha256:") || len(value) != 71 {
|
||||
return false
|
||||
}
|
||||
_, e := hex.DecodeString(value[7:])
|
||||
return e == nil && strings.ToLower(value) == value
|
||||
}
|
||||
|
||||
func readFile(path string, private bool) ([]byte, error) {
|
||||
if !filepath.IsAbs(path) {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
f, e := os.Open(path)
|
||||
if e != nil {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
defer f.Close()
|
||||
info, e := f.Stat()
|
||||
if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0022 != 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
if private && info.Mode().Perm()&0007 != 0 {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
b, e := io.ReadAll(io.LimitReader(f, maxBytes+1))
|
||||
if e != nil || len(b) > maxBytes {
|
||||
return nil, ErrRefused
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Check sends exactly one request with a cryptographically fresh nonce. The
|
||||
// returned envelope is the producer's authenticated typed interpretation.
|
||||
// Callers must execute only the request's exact operation and honor their own
|
||||
// execution boundary; a login decision is never a later resource decision.
|
||||
func (c *Client) Check(ctx context.Context, request api.CheckRequest) (api.DecisionEnvelope, error) {
|
||||
refuse := func() (api.DecisionEnvelope, error) { return api.DecisionEnvelope{}, ErrRefused }
|
||||
if c == nil || request.Purpose != "" || request.Tenant == "" || request.Subject.ID == "" || request.Subject.Type == "" || request.Resource.ID == "" || request.Resource.Type == "" || request.Resource.System == "" || request.Action == "" {
|
||||
return refuse()
|
||||
}
|
||||
if request.Subject.Tenant != request.Tenant || request.Resource.Tenant != request.Tenant {
|
||||
return refuse()
|
||||
}
|
||||
if request.PolicyVersion != "" && request.PolicyVersion != c.admission.PolicyVersion {
|
||||
return refuse()
|
||||
}
|
||||
// Use the producer's typed representation and preserve numeric lexemes. A
|
||||
// producer that rounds before hashing fails this join rather than weakening it.
|
||||
raw, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&request) != nil {
|
||||
return refuse()
|
||||
}
|
||||
if request.Context == nil {
|
||||
request.Context = map[string]any{}
|
||||
}
|
||||
if _, exists := request.Context[nonceKey]; exists {
|
||||
return refuse()
|
||||
}
|
||||
nonce := make([]byte, 32)
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
return refuse()
|
||||
}
|
||||
request.Context[nonceKey] = hex.EncodeToString(nonce)
|
||||
request.Context["decisionpep_json_profile"] = JSONProfile
|
||||
request.ID = hex.EncodeToString(nonce)
|
||||
request.PolicyVersion = c.admission.PolicyVersion
|
||||
raw, err = json.Marshal(request)
|
||||
if err != nil || len(raw) > maxBytes {
|
||||
return refuse()
|
||||
}
|
||||
token, err := readFile(c.admission.TokenFile, true)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
value := strings.TrimSpace(string(token))
|
||||
if value == "" || strings.ContainsAny(value, " \t\r\n") {
|
||||
return refuse()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.admission.Endpoint, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Access-Engine-JSON-Profile", JSONProfile)
|
||||
req.Header.Set("Authorization", "Bearer "+value)
|
||||
started := c.now().UTC()
|
||||
response, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return refuse()
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return refuse()
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxBytes+1))
|
||||
if err != nil || len(body) > maxBytes {
|
||||
return refuse()
|
||||
}
|
||||
envelope, err := sign.DecodeEnvelope(body)
|
||||
if err != nil || sign.Verify(envelope, c.keys) != nil {
|
||||
return refuse()
|
||||
}
|
||||
if c.validate(envelope, request, started, c.now().UTC()) != nil {
|
||||
return refuse()
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
func (c *Client) validate(e api.DecisionEnvelope, r api.CheckRequest, started, now time.Time) error {
|
||||
p := e.Provenance
|
||||
b := e.Binding
|
||||
l := e.Lifetime
|
||||
if e.ID == "" || e.ContractVersion != api.DecisionRecordContractV1 || e.Effect != api.DecisionEffectAllow || e.RequestID != r.ID || len(e.Obligations) != 0 || b == nil || l == nil {
|
||||
return ErrRefused
|
||||
}
|
||||
if p.Evaluator != c.admission.Evaluator || p.Mode != provenanceMode || p.PolicyPackage != c.admission.PolicyPackage || p.PolicyVersion != c.admission.PolicyVersion || p.PolicyPackageDigest != c.admission.PolicyDigest || p.RegistrySnapshotDigest != c.admission.RegistryDigest || e.MatchedPolicyVersion != p.PolicyVersion {
|
||||
return ErrRefused
|
||||
}
|
||||
if b.Purpose != "" || b.SubmittedRequestDigest != api.RequestDigest(r) || b.Tenant != r.Tenant || b.Action != r.Action || api.CanonicalDigest(b.Context) != api.CanonicalDigest(r.Context) {
|
||||
return ErrRefused
|
||||
}
|
||||
if !sameSubject(b.Subject, r.Subject) || !sameResource(b.Resource, r.Resource) || !sameSubject(e.Subject, b.Subject) || !sameResource(e.Resource, b.Resource) {
|
||||
return ErrRefused
|
||||
}
|
||||
evaluated := api.CheckRequest{Tenant: b.Tenant, Subject: b.Subject, Action: b.Action, Resource: b.Resource, Context: b.Context, Purpose: b.Purpose}
|
||||
if b.RequestDigest != api.RequestDigest(evaluated) {
|
||||
return ErrRefused
|
||||
}
|
||||
for k, v := range api.InputClaimDigests(r) {
|
||||
if p.InputClaimDigests[k] != v {
|
||||
return ErrRefused
|
||||
}
|
||||
}
|
||||
caller := p.Caller
|
||||
if caller == nil || caller.Mode != "enforce" || caller.Principal != c.admission.CallerPrincipal || caller.Audience != c.admission.CallerAudience {
|
||||
return ErrRefused
|
||||
}
|
||||
callerEnd, err := time.Parse(time.RFC3339Nano, caller.NotAfter)
|
||||
if err != nil || !now.Before(callerEnd) {
|
||||
return ErrRefused
|
||||
}
|
||||
decision, err := time.Parse(time.RFC3339Nano, p.DecisionTime)
|
||||
if err != nil || decision.Before(started.Add(-c.skew)) || decision.After(now.Add(c.skew)) {
|
||||
return ErrRefused
|
||||
}
|
||||
begin, err := time.Parse(time.RFC3339Nano, l.NotBefore)
|
||||
if err != nil || begin.After(now) {
|
||||
return ErrRefused
|
||||
}
|
||||
end, err := time.Parse(time.RFC3339Nano, l.ExpiresAt)
|
||||
if err != nil || !now.Before(end) || !end.After(begin) || end.Sub(begin) > c.maxTTL || end.After(callerEnd) {
|
||||
return ErrRefused
|
||||
}
|
||||
ttl, err := time.ParseDuration(l.TTL)
|
||||
if err != nil || l.Kind != api.DecisionLifetimeTTL || ttl <= 0 || ttl > c.maxTTL {
|
||||
return ErrRefused
|
||||
}
|
||||
// Producer CompleteDecision uses its exact decision instant for both bounds.
|
||||
// RFC3339 output can truncate subsecond precision, so do not invent lost time.
|
||||
if !begin.Equal(decision) || end.Sub(begin) != ttl {
|
||||
return ErrRefused
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameSubject(a, b api.SubjectRef) bool {
|
||||
return a.ID == b.ID && a.Type == b.Type && a.Tenant == b.Tenant
|
||||
}
|
||||
func sameResource(a, b api.ResourceRef) bool {
|
||||
return a.ID == b.ID && a.Type == b.Type && a.System == b.System && a.Tenant == b.Tenant
|
||||
}
|
||||
|
|
@ -0,0 +1,211 @@
|
|||
package decisionpep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
type transportFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func testClient(t *testing.T) (*Client, ed25519.PrivateKey, time.Time) {
|
||||
t.Helper()
|
||||
pub, key, e := ed25519.GenerateKey(rand.Reader)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
now := time.Date(2026, 10, 18, 1, 2, 3, 0, time.UTC)
|
||||
dir := t.TempDir()
|
||||
cert, e := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}, &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}, pub, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ca := filepath.Join(dir, "ca.pem")
|
||||
token := filepath.Join(dir, "token")
|
||||
if e = os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0600); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = os.WriteFile(token, []byte("synthetic-caller-token"), 0600); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a := Admission{Endpoint: "https://pdp.invalid/v1/check", CAFile: ca, TokenFile: token, Keys: map[string]string{"test-key": base64.RawURLEncoding.EncodeToString(pub)}, Evaluator: "flex-auth/local", PolicyPackage: "forgejo.application-access", PolicyVersion: "v1", PolicyDigest: "sha256:" + strings.Repeat("1", 64), RegistryDigest: "sha256:" + strings.Repeat("2", 64), CallerPrincipal: "system:serviceaccount:test:forgejo", CallerAudience: "access-engine", MaxTTL: "30s", MaxClockSkew: "1s"}
|
||||
c, e := New(a)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.now = func() time.Time { return now }
|
||||
return c, key, now
|
||||
}
|
||||
func testRequest() api.CheckRequest {
|
||||
return api.CheckRequest{Tenant: "tenant:test", Subject: api.SubjectRef{ID: "subject:test", Type: api.SubjectType("Human"), Tenant: "tenant:test", Attributes: map[string]any{"groups": []string{"engineers"}}}, Action: "application.access", Resource: api.ResourceRef{ID: "application:forgejo", Type: "application", System: "forgejo", Tenant: "tenant:test"}, Context: map[string]any{"big": json.Number("9007199254740993"), "fraction": json.Number("0.123456789123456789")}}
|
||||
}
|
||||
func envelope(c *Client, r api.CheckRequest, key ed25519.PrivateKey, now time.Time) api.DecisionEnvelope {
|
||||
e := api.DecisionEnvelope{ID: "test-decision", RequestID: r.ID, Effect: api.DecisionEffectAllow, MatchedPolicyVersion: c.admission.PolicyVersion, Subject: r.Subject, Resource: r.Resource, Binding: api.NewDecisionBindingFor(r, r), Provenance: api.DecisionProvenance{Evaluator: c.admission.Evaluator, Mode: provenanceMode, PolicyPackage: c.admission.PolicyPackage, PolicyVersion: c.admission.PolicyVersion, PolicyPackageDigest: c.admission.PolicyDigest, RegistrySnapshotDigest: c.admission.RegistryDigest, Caller: &api.CallerProvenance{Mode: "enforce", Principal: c.admission.CallerPrincipal, Audience: c.admission.CallerAudience, NotAfter: now.Add(time.Minute).Format(time.RFC3339Nano)}}}
|
||||
api.CompleteDecision(&e, r, api.DecisionCompletion{AllowTTL: "10s", Now: now})
|
||||
if sign.Sign(&e, key, "test-key") != nil {
|
||||
panic("test sign")
|
||||
}
|
||||
return e
|
||||
}
|
||||
func respond(t *testing.T, c *Client, key ed25519.PrivateKey, now time.Time, mutate func(*api.DecisionEnvelope), resign bool) {
|
||||
t.Helper()
|
||||
c.http = &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if req.Header.Get("Access-Engine-JSON-Profile") != JSONProfile {
|
||||
t.Fatal("missing lossless profile")
|
||||
}
|
||||
if req.Header.Get("Authorization") != "Bearer synthetic-caller-token" {
|
||||
t.Fatal("wrong synthetic caller token")
|
||||
}
|
||||
var r api.CheckRequest
|
||||
d := json.NewDecoder(req.Body)
|
||||
d.UseNumber()
|
||||
if d.Decode(&r) != nil {
|
||||
t.Fatal("request decode")
|
||||
}
|
||||
if r.Context["big"] != json.Number("9007199254740993") || r.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("request numeric precision lost")
|
||||
}
|
||||
if len(r.Context[nonceKey].(string)) != 64 || r.ID != r.Context[nonceKey] {
|
||||
t.Fatal("nonce")
|
||||
}
|
||||
e := envelope(c, r, key, now)
|
||||
if mutate != nil {
|
||||
mutate(&e)
|
||||
}
|
||||
if resign {
|
||||
if sign.Sign(&e, key, "test-key") != nil {
|
||||
t.Fatal("sign")
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(b))), Header: http.Header{}}, nil
|
||||
})}
|
||||
}
|
||||
func TestAuthenticDecisionProducerCanonicalPrecision(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, nil, false)
|
||||
e, err := c.Check(context.Background(), testRequest())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.Binding.Context["big"] != json.Number("9007199254740993") || e.Binding.Context["fraction"] != json.Number("0.123456789123456789") {
|
||||
t.Fatal("signed typed precision lost")
|
||||
}
|
||||
if sign.Verify(e, c.keys) != nil {
|
||||
t.Fatal("returned envelope not authentic producer bytes")
|
||||
}
|
||||
}
|
||||
func TestDecisionAdverseBindings(t *testing.T) {
|
||||
cases := map[string]func(*api.DecisionEnvelope){
|
||||
"unsigned": func(e *api.DecisionEnvelope) { e.Signature = api.UnsignedEnvelopeSignature() },
|
||||
"effect": func(e *api.DecisionEnvelope) { e.Effect = api.DecisionEffectDeny },
|
||||
"evaluator": func(e *api.DecisionEnvelope) { e.Provenance.Evaluator = "impostor" },
|
||||
"policy": func(e *api.DecisionEnvelope) { e.Provenance.PolicyPackage = "other" },
|
||||
"version": func(e *api.DecisionEnvelope) { e.Provenance.PolicyVersion = "v2" },
|
||||
"policy-digest": func(e *api.DecisionEnvelope) { e.Provenance.PolicyPackageDigest = "sha256:" + strings.Repeat("3", 64) },
|
||||
"registry": func(e *api.DecisionEnvelope) {
|
||||
e.Provenance.RegistrySnapshotDigest = "sha256:" + strings.Repeat("4", 64)
|
||||
},
|
||||
"tenant": func(e *api.DecisionEnvelope) { e.Binding.Tenant = "other" },
|
||||
"actor": func(e *api.DecisionEnvelope) { e.Binding.Subject.ID = "other" },
|
||||
"action": func(e *api.DecisionEnvelope) { e.Binding.Action = "write" },
|
||||
"resource": func(e *api.DecisionEnvelope) { e.Binding.Resource.ID = "other" },
|
||||
"purpose": func(e *api.DecisionEnvelope) { e.Binding.Purpose = "readback" },
|
||||
"submitted": func(e *api.DecisionEnvelope) { e.Binding.SubmittedRequestDigest = "wrong" },
|
||||
"context": func(e *api.DecisionEnvelope) { e.Binding.Context["fraction"] = json.Number("0.123456789123456788") },
|
||||
"legacy-numeric-profile": func(e *api.DecisionEnvelope) { e.Provenance.Mode = "standalone" },
|
||||
"caller-warn": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Mode = "warn" },
|
||||
"caller-principal": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Principal = "other" },
|
||||
"caller-audience": func(e *api.DecisionEnvelope) { e.Provenance.Caller.Audience = "other" },
|
||||
"caller-expired": func(e *api.DecisionEnvelope) { e.Provenance.Caller.NotAfter = "2020-01-01T00:00:00Z" },
|
||||
"stale-decision": func(e *api.DecisionEnvelope) { e.Provenance.DecisionTime = "2020-01-01T00:00:00Z" },
|
||||
"expired": func(e *api.DecisionEnvelope) { e.Lifetime.ExpiresAt = "2020-01-01T00:00:00Z" },
|
||||
"future-begin": func(e *api.DecisionEnvelope) { e.Lifetime.NotBefore = "2030-01-01T00:00:00Z" },
|
||||
"subnanosecond-expiry": func(e *api.DecisionEnvelope) { e.Lifetime.ExpiresAt = "2026-10-18T01:02:02.999999999Z" },
|
||||
"missing-TTL": func(e *api.DecisionEnvelope) { e.Lifetime = nil },
|
||||
"excess-TTL": func(e *api.DecisionEnvelope) { e.Lifetime.TTL = "1h" },
|
||||
"obligation": func(e *api.DecisionEnvelope) { e.Obligations = []api.Obligation{{Type: "unimplemented"}} },
|
||||
}
|
||||
for name, mutation := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, mutation, name != "unsigned")
|
||||
if _, err := c.Check(context.Background(), testRequest()); err == nil {
|
||||
t.Fatal("accepted wrong signed binding")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestSignatureForgeryAndReplay(t *testing.T) {
|
||||
t.Run("forged-payload", func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
respond(t, c, key, now, func(e *api.DecisionEnvelope) { e.Reason = "changed after signature" }, false)
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("forgery accepted")
|
||||
}
|
||||
})
|
||||
t.Run("wrong-key", func(t *testing.T) {
|
||||
c, _, now := testClient(t)
|
||||
_, key, _ := ed25519.GenerateKey(rand.Reader)
|
||||
respond(t, c, key, now, nil, false)
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("wrong key accepted")
|
||||
}
|
||||
})
|
||||
t.Run("replay", func(t *testing.T) {
|
||||
c, key, now := testClient(t)
|
||||
var saved []byte
|
||||
c.http = &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if saved == nil {
|
||||
var r api.CheckRequest
|
||||
d := json.NewDecoder(req.Body)
|
||||
d.UseNumber()
|
||||
if d.Decode(&r) != nil {
|
||||
t.Fatal("decode")
|
||||
}
|
||||
e := envelope(c, r, key, now)
|
||||
saved, _ = json.Marshal(e)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(saved)))}, nil
|
||||
})}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("old decision replay accepted for new nonce")
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestUnavailableAndPublicTokenFileRefuse(t *testing.T) {
|
||||
c, _, _ := testClient(t)
|
||||
c.http = &http.Client{Transport: transportFunc(func(*http.Request) (*http.Response, error) { return nil, io.ErrUnexpectedEOF })}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("unavailable allowed")
|
||||
}
|
||||
if e := os.Chmod(c.admission.TokenFile, 0644); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := c.Check(context.Background(), testRequest()); e == nil {
|
||||
t.Fatal("public token file allowed")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package decisionpep
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The distribution is a generated source slice, never a second implementation.
|
||||
func TestConsumerExportMatchesProducerSource(t *testing.T) {
|
||||
command := exec.Command("python3", filepath.Join("..", "..", "tools", "export_decisionpep_adapter.py"), "--check")
|
||||
if output, err := command.CombinedOutput(); err != nil {
|
||||
t.Fatalf("consumer export drift: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
// Package signfixture exposes producer signing only for synthetic consumer tests.
|
||||
// Callers supply test keys; this package contains no credentials or runtime signer.
|
||||
package signfixture
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"github.com/netkingdom/access-engine/internal/sign"
|
||||
"github.com/netkingdom/access-engine/pkg/api"
|
||||
)
|
||||
|
||||
// Sign uses the unchanged producer envelope format with a caller-owned fixture key.
|
||||
func Sign(envelope *api.DecisionEnvelope, key ed25519.PrivateKey, kid string) error {
|
||||
return sign.Sign(envelope, key, kid)
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
"""Export the Go 1.24 consumer slice from the producer's single source tree."""
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DESTINATION = ROOT / 'adapters/go/decisionpep'
|
||||
FILES = ['LICENSE', 'pkg/api/canonical.go', 'pkg/api/caring.go',
|
||||
'pkg/api/resource_manifest.go', 'internal/sign/sign.go',
|
||||
'pkg/decisionpep/client.go', 'pkg/decisionpep/client_test.go',
|
||||
'testsupport/signfixture/sign.go']
|
||||
BASELINE = {
|
||||
'pkg/api/canonical.go': 'a122a2e8cd524333b13c5939c7a3685e41efbe47497a64e0c7297c92b7f10d19',
|
||||
'pkg/api/caring.go': '1907156f0f889e7b9e9c14970cf7a86a20d00478a496efaf92c7231f27fec5e3',
|
||||
'pkg/api/resource_manifest.go': 'f0fa4080287d389ed48c2b1d6af96cc62e57ef72c902333f677f964420be133f',
|
||||
'internal/sign/sign.go': '0df9515922e90775ebbfac798361dcafb20da8a4213796b44e246b8a92046cde',
|
||||
'LICENSE': 'ff413f361a3b3bf44cf50f110fbcc4837064d57eefbcef89df2b43997c6262b6',
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--check', action='store_true')
|
||||
args = parser.parse_args()
|
||||
output = {name: (ROOT / name).read_bytes() for name in FILES}
|
||||
for name, digest in BASELINE.items():
|
||||
if hashlib.sha256(output[name]).hexdigest() != digest:
|
||||
raise SystemExit('Producer API/signature baseline changed; review the export contract before advancing it')
|
||||
output['go.mod'] = b'module github.com/netkingdom/access-engine\n\ngo 1.24\n'
|
||||
metadata = {
|
||||
'upstream': 'github.com/netkingdom/access-engine',
|
||||
'commit': 'd328a2601095686f74376d87791bff01e2a3a2a3',
|
||||
'exact_unchanged_files': BASELINE,
|
||||
'module': 'Standalone Go1.24 source slice with original module/import identity; no canonical/schema/signature modifications',
|
||||
'new_code': ['pkg/decisionpep/client.go'],
|
||||
'fixture_code': ['testsupport/signfixture/sign.go'],
|
||||
'source_of_truth': 'repository root; generated with tools/export_decisionpep_adapter.py',
|
||||
'exported_file_sha256': {name: hashlib.sha256(raw).hexdigest() for name, raw in sorted(output.items())},
|
||||
}
|
||||
output['producer-source.json'] = (json.dumps(metadata, indent=2) + '\n').encode()
|
||||
actual = {str(item.relative_to(DESTINATION)) for item in DESTINATION.rglob('*') if item.is_file()}
|
||||
if actual - set(output):
|
||||
raise SystemExit('Unexpected files in the generated consumer slice')
|
||||
if args.check:
|
||||
drift = [name for name, raw in output.items() if not (DESTINATION / name).is_file() or (DESTINATION / name).read_bytes() != raw]
|
||||
if drift:
|
||||
raise SystemExit('Generated consumer slice differs: ' + ', '.join(drift))
|
||||
else:
|
||||
for name, raw in output.items():
|
||||
path = DESTINATION / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(raw)
|
||||
print(json.dumps({'status': 'verified' if args.check else 'exported', 'files': len(output)}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
{
|
||||
"target": "adapter",
|
||||
"source_revision": "d328a2601095686f74376d87791bff01e2a3a2a3",
|
||||
"returncode": 0,
|
||||
"seconds": 36.93,
|
||||
"argv": [
|
||||
"bwrap",
|
||||
"--unshare-net",
|
||||
"--unshare-pid",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--symlink",
|
||||
"usr/bin",
|
||||
"/bin",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--bind",
|
||||
"/tmp/custodian-resume-adapter-7vn1h2qj",
|
||||
"/work",
|
||||
"--ro-bind",
|
||||
"/home/worsch/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.26.7.linux-amd64",
|
||||
"/toolchain",
|
||||
"--ro-bind",
|
||||
"/home/worsch/go/pkg/mod",
|
||||
"/modules",
|
||||
"--chdir",
|
||||
"/work/source",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"PATH",
|
||||
"/toolchain/bin:/usr/bin:/bin",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work/home",
|
||||
"--setenv",
|
||||
"GOTOOLCHAIN",
|
||||
"local",
|
||||
"--setenv",
|
||||
"GOPROXY",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOSUMDB",
|
||||
"off",
|
||||
"--setenv",
|
||||
"GOMODCACHE",
|
||||
"/modules",
|
||||
"--setenv",
|
||||
"GOCACHE",
|
||||
"/work/gocache",
|
||||
"--setenv",
|
||||
"GOMAXPROCS",
|
||||
"4",
|
||||
"--setenv",
|
||||
"CGO_ENABLED",
|
||||
"0",
|
||||
"--",
|
||||
"go",
|
||||
"test",
|
||||
"-p",
|
||||
"4",
|
||||
"-json",
|
||||
"./...",
|
||||
"-count=1"
|
||||
],
|
||||
"workspace": "/tmp/custodian-resume-adapter-7vn1h2qj",
|
||||
"network": "disabled",
|
||||
"pid_namespace": "private",
|
||||
"real_credentials": false,
|
||||
"canonical_owner_modified": false
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
{"Time":"2026-10-17T22:48:11.48829419Z","Action":"start","Package":"github.com/netkingdom/access-engine/internal/sign"}
|
||||
{"Time":"2026-10-17T22:48:11.488486519Z","Action":"output","Package":"github.com/netkingdom/access-engine/internal/sign","Output":"? \tgithub.com/netkingdom/access-engine/internal/sign\t[no test files]\n"}
|
||||
{"Time":"2026-10-17T22:48:11.488504301Z","Action":"skip","Package":"github.com/netkingdom/access-engine/internal/sign","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:11.488526646Z","Action":"start","Package":"github.com/netkingdom/access-engine/pkg/api"}
|
||||
{"Time":"2026-10-17T22:48:11.488534374Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/api","Output":"? \tgithub.com/netkingdom/access-engine/pkg/api\t[no test files]\n"}
|
||||
{"Time":"2026-10-17T22:48:11.48854083Z","Action":"skip","Package":"github.com/netkingdom/access-engine/pkg/api","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.653741624Z","Action":"start","Package":"github.com/netkingdom/access-engine/pkg/decisionpep"}
|
||||
{"Time":"2026-10-17T22:48:35.654267826Z","Action":"start","Package":"github.com/netkingdom/access-engine/testsupport/signfixture"}
|
||||
{"Time":"2026-10-17T22:48:35.654354689Z","Action":"output","Package":"github.com/netkingdom/access-engine/testsupport/signfixture","Output":"? \tgithub.com/netkingdom/access-engine/testsupport/signfixture\t[no test files]\n"}
|
||||
{"Time":"2026-10-17T22:48:35.654372895Z","Action":"skip","Package":"github.com/netkingdom/access-engine/testsupport/signfixture","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.67320409Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision"}
|
||||
{"Time":"2026-10-17T22:48:35.673264091Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision","Output":"=== RUN TestAuthenticDecisionProducerCanonicalPrecision\n"}
|
||||
{"Time":"2026-10-17T22:48:35.699530086Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision","Output":"--- PASS: TestAuthenticDecisionProducerCanonicalPrecision (0.02s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.699633018Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestAuthenticDecisionProducerCanonicalPrecision","Elapsed":0.02}
|
||||
{"Time":"2026-10-17T22:48:35.699688816Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings"}
|
||||
{"Time":"2026-10-17T22:48:35.699698735Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings","Output":"=== RUN TestDecisionAdverseBindings\n"}
|
||||
{"Time":"2026-10-17T22:48:35.699708573Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator"}
|
||||
{"Time":"2026-10-17T22:48:35.699717645Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator","Output":"=== RUN TestDecisionAdverseBindings/evaluator\n"}
|
||||
{"Time":"2026-10-17T22:48:35.699765346Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator","Output":"--- PASS: TestDecisionAdverseBindings/evaluator (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.699777943Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/evaluator","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.699788682Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy"}
|
||||
{"Time":"2026-10-17T22:48:35.699796582Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy","Output":"=== RUN TestDecisionAdverseBindings/policy\n"}
|
||||
{"Time":"2026-10-17T22:48:35.714060835Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy","Output":"--- PASS: TestDecisionAdverseBindings/policy (0.02s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.720807009Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy","Elapsed":0.02}
|
||||
{"Time":"2026-10-17T22:48:35.72086655Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource"}
|
||||
{"Time":"2026-10-17T22:48:35.72087829Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource","Output":"=== RUN TestDecisionAdverseBindings/resource\n"}
|
||||
{"Time":"2026-10-17T22:48:35.720894178Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource","Output":"--- PASS: TestDecisionAdverseBindings/resource (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.72090352Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/resource","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.72091215Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose"}
|
||||
{"Time":"2026-10-17T22:48:35.720919841Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose","Output":"=== RUN TestDecisionAdverseBindings/purpose\n"}
|
||||
{"Time":"2026-10-17T22:48:35.720929562Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose","Output":"--- PASS: TestDecisionAdverseBindings/purpose (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.720938156Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/purpose","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.720946235Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL"}
|
||||
{"Time":"2026-10-17T22:48:35.720953629Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL","Output":"=== RUN TestDecisionAdverseBindings/missing-TTL\n"}
|
||||
{"Time":"2026-10-17T22:48:35.727413677Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL","Output":"--- PASS: TestDecisionAdverseBindings/missing-TTL (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.736852251Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/missing-TTL","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:48:35.740254536Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation"}
|
||||
{"Time":"2026-10-17T22:48:35.74029625Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation","Output":"=== RUN TestDecisionAdverseBindings/obligation\n"}
|
||||
{"Time":"2026-10-17T22:48:35.740313121Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation","Output":"--- PASS: TestDecisionAdverseBindings/obligation (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.740322328Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/obligation","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.740331886Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect"}
|
||||
{"Time":"2026-10-17T22:48:35.740338595Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect","Output":"=== RUN TestDecisionAdverseBindings/effect\n"}
|
||||
{"Time":"2026-10-17T22:48:35.742114537Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect","Output":"--- PASS: TestDecisionAdverseBindings/effect (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.748836855Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/effect","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:48:35.748899867Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest"}
|
||||
{"Time":"2026-10-17T22:48:35.748909299Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest","Output":"=== RUN TestDecisionAdverseBindings/policy-digest\n"}
|
||||
{"Time":"2026-10-17T22:48:35.752796499Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest","Output":"--- PASS: TestDecisionAdverseBindings/policy-digest (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.752904977Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/policy-digest","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:48:35.752925374Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry"}
|
||||
{"Time":"2026-10-17T22:48:35.752934319Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry","Output":"=== RUN TestDecisionAdverseBindings/registry\n"}
|
||||
{"Time":"2026-10-17T22:48:35.760883817Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry","Output":"--- PASS: TestDecisionAdverseBindings/registry (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.760938588Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/registry","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:48:35.760952041Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/legacy-numeric-profile"}
|
||||
{"Time":"2026-10-17T22:48:35.760959742Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/legacy-numeric-profile","Output":"=== RUN TestDecisionAdverseBindings/legacy-numeric-profile\n"}
|
||||
{"Time":"2026-10-17T22:48:35.760971356Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/legacy-numeric-profile","Output":"--- PASS: TestDecisionAdverseBindings/legacy-numeric-profile (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.761225516Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/legacy-numeric-profile","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.761244372Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience"}
|
||||
{"Time":"2026-10-17T22:48:35.761252072Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience","Output":"=== RUN TestDecisionAdverseBindings/caller-audience\n"}
|
||||
{"Time":"2026-10-17T22:48:35.763819752Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience","Output":"--- PASS: TestDecisionAdverseBindings/caller-audience (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.7640287Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-audience","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.764219225Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired"}
|
||||
{"Time":"2026-10-17T22:48:35.764243202Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired","Output":"=== RUN TestDecisionAdverseBindings/caller-expired\n"}
|
||||
{"Time":"2026-10-17T22:48:35.767715831Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired","Output":"--- PASS: TestDecisionAdverseBindings/caller-expired (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.767939378Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-expired","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.77311219Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision"}
|
||||
{"Time":"2026-10-17T22:48:35.773298415Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision","Output":"=== RUN TestDecisionAdverseBindings/stale-decision\n"}
|
||||
{"Time":"2026-10-17T22:48:35.773385061Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision","Output":"--- PASS: TestDecisionAdverseBindings/stale-decision (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.773403907Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/stale-decision","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.773414963Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry"}
|
||||
{"Time":"2026-10-17T22:48:35.773481005Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry","Output":"=== RUN TestDecisionAdverseBindings/subnanosecond-expiry\n"}
|
||||
{"Time":"2026-10-17T22:48:35.774732817Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry","Output":"--- PASS: TestDecisionAdverseBindings/subnanosecond-expiry (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.774779463Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/subnanosecond-expiry","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.774795496Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version"}
|
||||
{"Time":"2026-10-17T22:48:35.77480445Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version","Output":"=== RUN TestDecisionAdverseBindings/version\n"}
|
||||
{"Time":"2026-10-17T22:48:35.779721991Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version","Output":"--- PASS: TestDecisionAdverseBindings/version (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.779932724Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/version","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.780073465Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant"}
|
||||
{"Time":"2026-10-17T22:48:35.780091112Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant","Output":"=== RUN TestDecisionAdverseBindings/tenant\n"}
|
||||
{"Time":"2026-10-17T22:48:35.792895491Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant","Output":"--- PASS: TestDecisionAdverseBindings/tenant (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.792963653Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/tenant","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.792977187Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor"}
|
||||
{"Time":"2026-10-17T22:48:35.792992571Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor","Output":"=== RUN TestDecisionAdverseBindings/actor\n"}
|
||||
{"Time":"2026-10-17T22:48:35.793040065Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor","Output":"--- PASS: TestDecisionAdverseBindings/actor (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.793051895Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/actor","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.793061336Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action"}
|
||||
{"Time":"2026-10-17T22:48:35.793069199Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action","Output":"=== RUN TestDecisionAdverseBindings/action\n"}
|
||||
{"Time":"2026-10-17T22:48:35.793078983Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action","Output":"--- PASS: TestDecisionAdverseBindings/action (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.804478715Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/action","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.804537327Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted"}
|
||||
{"Time":"2026-10-17T22:48:35.804547291Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted","Output":"=== RUN TestDecisionAdverseBindings/submitted\n"}
|
||||
{"Time":"2026-10-17T22:48:35.804560853Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted","Output":"--- PASS: TestDecisionAdverseBindings/submitted (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.804569582Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/submitted","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.804578076Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context"}
|
||||
{"Time":"2026-10-17T22:48:35.804585543Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context","Output":"=== RUN TestDecisionAdverseBindings/context\n"}
|
||||
{"Time":"2026-10-17T22:48:35.805271322Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context","Output":"--- PASS: TestDecisionAdverseBindings/context (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.805332712Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/context","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.805344074Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL"}
|
||||
{"Time":"2026-10-17T22:48:35.805352523Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL","Output":"=== RUN TestDecisionAdverseBindings/excess-TTL\n"}
|
||||
{"Time":"2026-10-17T22:48:35.809190572Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL","Output":"--- PASS: TestDecisionAdverseBindings/excess-TTL (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.809262638Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/excess-TTL","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.809277435Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned"}
|
||||
{"Time":"2026-10-17T22:48:35.809286921Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned","Output":"=== RUN TestDecisionAdverseBindings/unsigned\n"}
|
||||
{"Time":"2026-10-17T22:48:35.811654526Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned","Output":"--- PASS: TestDecisionAdverseBindings/unsigned (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.811718891Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/unsigned","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.8117379Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn"}
|
||||
{"Time":"2026-10-17T22:48:35.811748441Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn","Output":"=== RUN TestDecisionAdverseBindings/caller-warn\n"}
|
||||
{"Time":"2026-10-17T22:48:35.816424822Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn","Output":"--- PASS: TestDecisionAdverseBindings/caller-warn (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.816483732Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-warn","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.82205089Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal"}
|
||||
{"Time":"2026-10-17T22:48:35.822103551Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal","Output":"=== RUN TestDecisionAdverseBindings/caller-principal\n"}
|
||||
{"Time":"2026-10-17T22:48:35.822119628Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal","Output":"--- PASS: TestDecisionAdverseBindings/caller-principal (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.822128682Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/caller-principal","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.822138997Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired"}
|
||||
{"Time":"2026-10-17T22:48:35.822146391Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired","Output":"=== RUN TestDecisionAdverseBindings/expired\n"}
|
||||
{"Time":"2026-10-17T22:48:35.823347209Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired","Output":"--- PASS: TestDecisionAdverseBindings/expired (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.823402828Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/expired","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.823413567Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin"}
|
||||
{"Time":"2026-10-17T22:48:35.823421484Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin","Output":"=== RUN TestDecisionAdverseBindings/future-begin\n"}
|
||||
{"Time":"2026-10-17T22:48:35.826501101Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin","Output":"--- PASS: TestDecisionAdverseBindings/future-begin (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.826614024Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings/future-begin","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.826650779Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings","Output":"--- PASS: TestDecisionAdverseBindings (0.14s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.826667839Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestDecisionAdverseBindings","Elapsed":0.14}
|
||||
{"Time":"2026-10-17T22:48:35.826721672Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay"}
|
||||
{"Time":"2026-10-17T22:48:35.826734233Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay","Output":"=== RUN TestSignatureForgeryAndReplay\n"}
|
||||
{"Time":"2026-10-17T22:48:35.826935425Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload"}
|
||||
{"Time":"2026-10-17T22:48:35.827143685Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload","Output":"=== RUN TestSignatureForgeryAndReplay/forged-payload\n"}
|
||||
{"Time":"2026-10-17T22:48:35.830331845Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload","Output":"--- PASS: TestSignatureForgeryAndReplay/forged-payload (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.830389537Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/forged-payload","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.830406706Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key"}
|
||||
{"Time":"2026-10-17T22:48:35.830414822Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key","Output":"=== RUN TestSignatureForgeryAndReplay/wrong-key\n"}
|
||||
{"Time":"2026-10-17T22:48:35.842566184Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key","Output":"--- PASS: TestSignatureForgeryAndReplay/wrong-key (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.842720289Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/wrong-key","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:48:35.842745438Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay"}
|
||||
{"Time":"2026-10-17T22:48:35.842753941Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay","Output":"=== RUN TestSignatureForgeryAndReplay/replay\n"}
|
||||
{"Time":"2026-10-17T22:48:35.842801994Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay","Output":"--- PASS: TestSignatureForgeryAndReplay/replay (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.842813122Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay/replay","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.842822076Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay","Output":"--- PASS: TestSignatureForgeryAndReplay (0.01s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.84283048Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestSignatureForgeryAndReplay","Elapsed":0.01}
|
||||
{"Time":"2026-10-17T22:48:35.842838118Z","Action":"run","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse"}
|
||||
{"Time":"2026-10-17T22:48:35.84284433Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse","Output":"=== RUN TestUnavailableAndPublicTokenFileRefuse\n"}
|
||||
{"Time":"2026-10-17T22:48:35.844932031Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse","Output":"--- PASS: TestUnavailableAndPublicTokenFileRefuse (0.00s)\n"}
|
||||
{"Time":"2026-10-17T22:48:35.845001202Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Test":"TestUnavailableAndPublicTokenFileRefuse","Elapsed":0}
|
||||
{"Time":"2026-10-17T22:48:35.845047452Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Output":"PASS\n"}
|
||||
{"Time":"2026-10-17T22:48:35.856231621Z","Action":"output","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Output":"ok \tgithub.com/netkingdom/access-engine/pkg/decisionpep\t0.202s\n"}
|
||||
{"Time":"2026-10-17T22:48:35.856286744Z","Action":"pass","Package":"github.com/netkingdom/access-engine/pkg/decisionpep","Elapsed":0.203}
|
||||
Loading…
Add table
Add a link
Reference in a new issue