diff --git a/build/forgejo/README.md b/build/forgejo/README.md index ff29075..56d2a7b 100644 --- a/build/forgejo/README.md +++ b/build/forgejo/README.md @@ -1,7 +1,11 @@ # Forgejo release preparation (build only) -The Apps Makefile targets package the independently reviewed seven-path Forgejo -11.0.3 source extension. They never deploy, push, change default values or choose +The Apps Makefile targets package the digest-bound 37-path Forgejo 11.0.3 +source candidate in `forgejo-security-extension.patch`. It combines the original +three-group any-of gate, private secret-file input, private source-operation DB +primitives and the producer-owned Access Engine client in the OIDC callback. +Coordinator source tests and complete release checks are recorded separately; +independent owner review and operational admission of this revision remain open. They never deploy, push, change default values or choose an operational image. Third-party application source is expanded only into a new `/tmp` workspace; this repository retains a release input lock and exact reviewed patch, not a second source-code tree. Upstream source ownership and publication @@ -70,3 +74,40 @@ private secret-input boundary, type/case/descriptor re-freeze, current operation inverse sessions, durable journal and application/Helm writer exclusion are separate gates. Helm omission/rollback does not remove persisted OAuth source. The existing case gate is compatibility code, not a single-PDP exception. + +## KeyCape identity and callback admission + +The callback independently verifies the ID token against owner-admitted public +keys, algorithms, issuer, audience and token type. Public trust is loaded from +`FORGEJO_ACCESS_ENGINE_ADMISSION_FILE`; only an absolute private file reference +is used for the PDP caller token. No admission file or operational keys are +supplied by this build. New fields `tenant_source_claim` and +`max_authentication_age` are mandatory. The KeyCape v0.3 profile uses +`assurance_claim: assurance` and `tenant_source_claim: tenant_source`. Maximum +identity age and maximum authentication age are separate positive durations +chosen by the owner, not implicit defaults. + +The signed assurance object preserves `level`, `methods`, boolean `mfa`, +`source: key-cape` and integer `at`. Its authentication time must not follow +issuance or the current time, and must satisfy the admitted authentication-age +bound. Identity validity ends at the earliest token expiration, issued-at age +bound or authentication-age bound. Directory, registration and default tenant +provenance remain distinct in the request. Mutable UserInfo cannot replace +these authenticated facts. Current UserInfo subject and the Goth subject must +match the independently verified token; the three required group alternatives +remain policy input. + +The parser also represents valid lower-assurance facts. Application policy +continues to decide authorization. The Check client and unchanged canonical +signature bytes are a generated source slice of Access Engine ca0cb757; Forgejo +adds no policy evaluator. Exact caller/policy/registry/signer/request/lifetime +pins, an authenticated HTTPS connection and a current ALLOW are required. +Synthetic callback fixtures test ALLOW, DENY and adverse cases, including an ID +token serialized by the actual pinned KeyCape handler. Those fixtures do not +prove an actual browser, factor, custody or native rollout. + +The current integration covers this guarded OIDC callback. Ongoing application +HTTP/API/Git/SSH paths, current operation/inverse sessions, durable private +evidence and retention, PostgreSQL/native proof and exclusion of all release +writers remain open in RAPPS-WP-0016-T08/T09 and NK-WP-0048-T43. An old image +approval or source test result cannot admit this candidate. diff --git a/build/forgejo/forgejo-security-extension.patch b/build/forgejo/forgejo-security-extension.patch new file mode 100644 index 0000000..cd0fb52 --- /dev/null +++ b/build/forgejo/forgejo-security-extension.patch @@ -0,0 +1,4559 @@ +--- a/cmd/admin_auth_oauth.go ++++ b/cmd/admin_auth_oauth.go +@@ -9,6 +9,7 @@ + "net/url" + + auth_model "forgejo.org/models/auth" ++ "forgejo.org/models/db" + "forgejo.org/services/auth/source/oauth2" + + "github.com/urfave/cli/v2" +@@ -35,6 +36,10 @@ + Name: "secret", + Value: "", + Usage: "Client Secret", ++ }, ++ &cli.StringFlag{ ++ Name: "secret-file", ++ Usage: "Read a 64-byte base64url client secret from an admitted read-only regular file", + }, + &cli.StringFlag{ + Name: "auto-discover-url", +@@ -94,6 +99,10 @@ + Name: "required-claim-value", + Value: "", + Usage: "Claim value that has to be set to allow users to login with this source", ++ }, ++ &cli.StringSliceFlag{ ++ Name: "required-claim-values", ++ Usage: "Require any one exact array value from current OpenID Connect UserInfo (cannot combine with required-claim-value)", + }, + &cli.StringFlag{ + Name: "group-claim-name", +@@ -160,6 +169,7 @@ + Scopes: c.StringSlice("scopes"), + RequiredClaimName: c.String("required-claim-name"), + RequiredClaimValue: c.String("required-claim-value"), ++ RequiredClaimValues: c.StringSlice("required-claim-values"), + GroupClaimName: c.String("group-claim-name"), + AdminGroup: c.String("admin-group"), + RestrictedGroup: c.String("restricted-group"), +@@ -169,14 +179,31 @@ + } + + func runAddOauth(c *cli.Context) error { ++ secret, selected, err := oauthSecretInput(c) ++ if err != nil { ++ return err ++ } + ctx, cancel := installSignals() + defer cancel() ++ ctx = db.WithSensitiveSQL(ctx) + + if err := initDB(ctx); err != nil { + return err + } ++ if db.SQLLoggingEnabled(ctx) { ++ return errors.New("OAuth configuration requires SQL logging disabled") ++ } + + config := parseOAuth2Config(c) ++ if selected { ++ config.ClientSecret = secret ++ } ++ if err := oauth2.ValidateRequiredClaimValues(config.RequiredClaimName, config.RequiredClaimValue, config.RequiredClaimValues); err != nil { ++ return err ++ } ++ if config.RequiredClaimValues != nil && config.Provider != "openidConnect" { ++ return errors.New("required-claim-values requires openidConnect") ++ } + if config.Provider == "openidConnect" { + discoveryURL, err := url.Parse(config.OpenIDConnectAutoDiscoveryURL) + if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") { +@@ -184,24 +211,36 @@ + } + } + +- return auth_model.CreateSource(ctx, &auth_model.Source{ ++ err = auth_model.CreateSource(ctx, &auth_model.Source{ + Type: auth_model.OAuth2, + Name: c.String("name"), + IsActive: true, + Cfg: config, + }) ++ if err != nil && c.IsSet("secret-file") { ++ return errors.New("OAuth source creation failed") ++ } ++ return err + } + + func runUpdateOauth(c *cli.Context) error { ++ secret, selected, err := oauthSecretInput(c) ++ if err != nil { ++ return err ++ } + if !c.IsSet("id") { + return errors.New("--id flag is missing") + } + + ctx, cancel := installSignals() + defer cancel() ++ ctx = db.WithSensitiveSQL(ctx) + + if err := initDB(ctx); err != nil { + return err ++ } ++ if db.SQLLoggingEnabled(ctx) { ++ return errors.New("OAuth configuration requires SQL logging disabled") + } + + source, err := auth_model.GetSourceByID(ctx, c.Int64("id")) +@@ -209,7 +248,10 @@ + return err + } + +- oAuth2Config := source.Cfg.(*oauth2.Source) ++ oAuth2Config, ok := source.Cfg.(*oauth2.Source) ++ if !ok { ++ return errors.New("authentication source is not OAuth2") ++ } + + if c.IsSet("name") { + source.Name = c.String("name") +@@ -223,8 +265,8 @@ + oAuth2Config.ClientID = c.String("key") + } + +- if c.IsSet("secret") { +- oAuth2Config.ClientSecret = c.String("secret") ++ if selected { ++ oAuth2Config.ClientSecret = secret + } + + if c.IsSet("auto-discover-url") { +@@ -244,6 +286,10 @@ + } + if c.IsSet("required-claim-value") { + oAuth2Config.RequiredClaimValue = c.String("required-claim-value") ++ } ++ ++ if c.IsSet("required-claim-values") { ++ oAuth2Config.RequiredClaimValues = c.StringSlice("required-claim-values") + } + + if c.IsSet("group-claim-name") { +@@ -293,7 +339,30 @@ + } + + oAuth2Config.CustomURLMapping = customURLMapping ++ if err := oauth2.ValidateRequiredClaimValues(oAuth2Config.RequiredClaimName, oAuth2Config.RequiredClaimValue, oAuth2Config.RequiredClaimValues); err != nil { ++ return err ++ } ++ if oAuth2Config.RequiredClaimValues != nil && oAuth2Config.Provider != "openidConnect" { ++ return errors.New("required-claim-values requires openidConnect") ++ } + source.Cfg = oAuth2Config + +- return auth_model.UpdateSource(ctx, source) ++ err = auth_model.UpdateSource(ctx, source) ++ if err != nil && c.IsSet("secret-file") { ++ return errors.New("OAuth source update failed") ++ } ++ return err + } ++ ++// Resolve before opening the DB or mutating a loaded source. Never store the ++// resolved bytes in the CLI context: they must not become flag/argv diagnostics. ++func oauthSecretInput(c *cli.Context) (string, bool, error) { ++ if c.IsSet("secret-file") { ++ if c.IsSet("secret") { ++ return "", false, errors.New("secret and secret-file are mutually exclusive") ++ } ++ value, err := readOAuthSecretFile(c.String("secret-file")) ++ return value, true, err ++ } ++ return c.String("secret"), c.IsSet("secret"), nil ++} +--- /dev/null ++++ b/cmd/admin_auth_oauth_secret_linux.go +@@ -0,0 +1,114 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++ ++//go:build linux ++ ++package cmd ++ ++import ( ++ "errors" ++ "io" ++ "os" ++ "path/filepath" ++ "strings" ++ ++ "golang.org/x/sys/unix" ++) ++ ++var errOAuthSecretFile = errors.New("secret-file input refused") ++ ++// This checks DAC and mount properties, not namespace, Secret provenance or ++// operation authority. Admission must bind the exact workload/mount/reader set. ++// Kubernetes Secret subPath leaves are root-owned; fsGroup can provide 0440 ++// access. Requiring euid ownership would incorrectly refuse that supported case. ++func readOAuthSecretFile(path string) (string, error) { ++ if len(path) > 4096 || !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsRune(path, 0) { ++ return "", errOAuthSecretFile ++ } ++ parts := strings.Split(strings.TrimPrefix(path, "/"), "/") ++ if len(parts) < 2 { ++ return "", errOAuthSecretFile ++ } ++ dir, err := unix.Open("/", unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) ++ if err != nil { ++ return "", errOAuthSecretFile ++ } ++ defer func() { unix.Close(dir) }() ++ for _, part := range parts[:len(parts)-1] { ++ var st unix.Stat_t ++ if unix.Fstat(dir, &st) != nil || !safeOAuthSecretParent(st) { ++ return "", errOAuthSecretFile ++ } ++ next, err := unix.Openat(dir, part, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) ++ if err != nil { ++ return "", errOAuthSecretFile ++ } ++ unix.Close(dir) ++ dir = next ++ } ++ var parent unix.Stat_t ++ if unix.Fstat(dir, &parent) != nil || !safeOAuthSecretParent(parent) { ++ return "", errOAuthSecretFile ++ } ++ // Nonblocking is necessary: reject a FIFO without waiting for a writer. ++ fd, err := unix.Openat(dir, parts[len(parts)-1], unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) ++ if err != nil { ++ return "", errOAuthSecretFile ++ } ++ f := os.NewFile(uintptr(fd), "private OAuth input") ++ defer f.Close() ++ return readOAuthSecretFD(f, dir, parts[len(parts)-1]) ++} ++ ++func readOAuthSecretFD(f *os.File, dir int, leaf string) (string, error) { ++ fd := int(f.Fd()) ++ var before, after, named unix.Stat_t ++ var mount unix.Statfs_t ++ if unix.Fstat(fd, &before) != nil || !safeOAuthSecretLeaf(before) || unix.Fstatfs(fd, &mount) != nil || mount.Flags&unix.ST_RDONLY == 0 { ++ return "", errOAuthSecretFile ++ } ++ // mint-secret uses secrets.token_urlsafe(48): exactly 64 ASCII characters, ++ // no padding/newline. Bounded read still detects a concurrent size increase. ++ data, err := io.ReadAll(io.LimitReader(f, 65)) ++ defer clear(data) ++ if err != nil || len(data) != 64 { ++ return "", errOAuthSecretFile ++ } ++ for _, b := range data { ++ if !(b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || b == '-' || b == '_') { ++ return "", errOAuthSecretFile ++ } ++ } ++ if unix.Fstat(fd, &after) != nil || !sameOAuthSecretFile(before, after) || unix.Fstatat(dir, leaf, &named, unix.AT_SYMLINK_NOFOLLOW) != nil || !sameOAuthSecretFile(before, named) { ++ return "", errOAuthSecretFile ++ } ++ return string(data), nil ++} ++ ++func safeOAuthSecretParent(st unix.Stat_t) bool { ++ return st.Mode&unix.S_IFMT == unix.S_IFDIR && (st.Uid == 0 || st.Uid == uint32(os.Geteuid())) && st.Mode&0022 == 0 ++} ++ ++func safeOAuthSecretLeaf(st unix.Stat_t) bool { ++ if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1 || st.Size != 64 || st.Mode&07337 != 0 || (st.Uid != 0 && st.Uid != uint32(os.Geteuid())) { ++ return false ++ } ++ if st.Mode&0040 != 0 { ++ groups, err := os.Getgroups() ++ if err != nil { ++ return false ++ } ++ member := st.Gid == uint32(os.Getegid()) ++ for _, gid := range groups { ++ member = member || st.Gid == uint32(gid) ++ } ++ if !member { ++ return false ++ } ++ } ++ return true ++} ++ ++func sameOAuthSecretFile(a, b unix.Stat_t) bool { ++ return a.Dev == b.Dev && a.Ino == b.Ino && a.Mode == b.Mode && a.Nlink == b.Nlink && a.Uid == b.Uid && a.Gid == b.Gid && a.Size == b.Size && a.Mtim == b.Mtim && a.Ctim == b.Ctim ++} +--- /dev/null ++++ b/cmd/admin_auth_oauth_secret_linux_test.go +@@ -0,0 +1,79 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++ ++//go:build linux ++ ++package cmd ++ ++import ( ++ "golang.org/x/sys/unix" ++ "os" ++ "testing" ++) ++ ++func TestPrivateSecretMetadata(t *testing.T) { ++ st := unix.Stat_t{Mode: unix.S_IFREG | 0440, Uid: 0, Gid: uint32(os.Getegid()), Nlink: 1, Size: 64} ++ if !safeOAuthSecretLeaf(st) { ++ t.Fatal("root-owned fsGroup-readable Secret subPath refused") ++ } ++ for _, mode := range []uint32{0444, 0640, 0540, 0460, 0441, 0440 | unix.S_ISUID, 0440 | unix.S_ISGID, 0440 | unix.S_ISVTX} { ++ x := st ++ x.Mode = unix.S_IFREG | mode ++ if safeOAuthSecretLeaf(x) { ++ t.Fatalf("unsafe mode accepted: %o", mode) ++ } ++ } ++ for _, mutate := range []func(*unix.Stat_t){func(x *unix.Stat_t) { x.Uid = 123456 }, func(x *unix.Stat_t) { x.Nlink = 2 }, func(x *unix.Stat_t) { x.Size = 63 }, func(x *unix.Stat_t) { x.Mode = unix.S_IFIFO | 0400 }, func(x *unix.Stat_t) { x.Gid = 123456 }} { ++ x := st ++ mutate(&x) ++ if safeOAuthSecretLeaf(x) { ++ t.Fatal("unsafe metadata accepted") ++ } ++ } ++ if !safeOAuthSecretParent(unix.Stat_t{Mode: unix.S_IFDIR | 0755, Uid: 0}) { ++ t.Fatal("root parent refused") ++ } ++ if safeOAuthSecretParent(unix.Stat_t{Mode: unix.S_IFDIR | 0775, Uid: 0}) { ++ t.Fatal("group writable parent accepted") ++ } ++ for _, mutate := range []func(*unix.Stat_t){func(x *unix.Stat_t) { x.Dev++ }, func(x *unix.Stat_t) { x.Ino++ }, func(x *unix.Stat_t) { x.Ctim.Nsec++ }, func(x *unix.Stat_t) { x.Mtim.Nsec++ }, func(x *unix.Stat_t) { x.Size++ }, func(x *unix.Stat_t) { x.Uid++ }, func(x *unix.Stat_t) { x.Gid++ }, func(x *unix.Stat_t) { x.Nlink++ }, func(x *unix.Stat_t) { x.Mode++ }} { ++ x := st ++ mutate(&x) ++ if sameOAuthSecretFile(st, x) { ++ t.Fatal("changed file considered stable") ++ } ++ } ++ x := st ++ x.Atim.Nsec++ ++ if !sameOAuthSecretFile(st, x) { ++ t.Fatal("read-induced atime change refused") ++ } ++} ++ ++// Actual Linux descriptors and namespace read-only bind mounts, not mocked stat ++// metadata. A writable alias lets the fixture simulate replacement after open. ++func TestPrivateSecretOpenedFileReplacement(t *testing.T) { ++ if _, err := os.Stat("/run/forgejo-oidc/race"); os.IsNotExist(err) { ++ t.Skip("requires isolated read-only bind fixture") ++ } ++ dir, err := unix.Open("/run/forgejo-oidc", unix.O_PATH|unix.O_DIRECTORY, 0) ++ if err != nil { ++ t.Fatal(err) ++ } ++ defer unix.Close(dir) ++ f, err := os.Open("/run/forgejo-oidc/race") ++ if err != nil { ++ t.Fatal(err) ++ } ++ defer f.Close() ++ // Preserve the opened inode with one link; replace only the named leaf. ++ if err := os.Rename("/run/writable-input/race", "/run/writable-input/race-backup"); err != nil { ++ t.Fatal(err) ++ } ++ if err := os.Rename("/run/writable-input/race-replacement", "/run/writable-input/race"); err != nil { ++ t.Fatal(err) ++ } ++ if value, err := readOAuthSecretFD(f, dir, "race"); err != errOAuthSecretFile || value != "" { ++ t.Fatal("replaced leaf accepted") ++ } ++} +--- /dev/null ++++ b/cmd/admin_auth_oauth_secret_other.go +@@ -0,0 +1,12 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++ ++//go:build !linux ++ ++package cmd ++ ++import "errors" ++ ++func readOAuthSecretFile(string) (string, error) { ++ return "", errors.New("secret-file input refused") ++} +--- a/go.mod ++++ b/go.mod +@@ -255,3 +255,7 @@ + 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 +--- /dev/null ++++ b/models/auth/source_operation.go +@@ -0,0 +1,430 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++ ++package auth ++ ++// This owner-confined database primitive is NOT an authorization boundary. ++// No CLI/web/API route exposes it. The admitted runtime must separately obtain ++// fresh authenticated apply/inverse sessions and retain signed public evidence. ++// Configurations and private journal rows must never leave database custody. ++ ++import ( ++ "context" ++ "encoding/json" ++ "errors" ++ "reflect" ++ "regexp" ++ "sort" ++ ++ "forgejo.org/models/db" ++ "forgejo.org/modules/setting" ++ "forgejo.org/modules/timeutil" ++ "xorm.io/xorm" ++) ++ ++var ( ++ ErrSourceOperationConflict = errors.New("source operation requires owner reconciliation") ++ ErrSourceOperationStorage = errors.New("source operation storage failure; reconcile before retry") ++ ErrSourceOperationUnsupported = errors.New("source operation requires standalone SQLite/PostgreSQL transaction with SQL logging disabled") ++ operationIDPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]{7,127}$`) ++) ++ ++// Private source rows deliberately bypass Config decoding: decoding and ++// reserializing can erase unknown fields, including a gate on an older image. ++type sourceOperationRow struct { ++ ID int64 `xorm:"pk autoincr"` ++ Type Type ++ Name string ++ IsActive bool ++ IsSyncEnabled bool ++ Cfg string `xorm:"TEXT"` ++ CreatedUnix timeutil.TimeStamp ++ UpdatedUnix timeutil.TimeStamp ++} ++ ++func (sourceOperationRow) TableName() string { return "login_source" } ++ ++// The whole inventory, including private configs, stays in the owner's database. ++// Neither journal payload nor its digest is a public result. ++type sourceOperationJournal struct { ++ OperationID string `xorm:"pk VARCHAR(128)"` ++ CaseID string `xorm:"VARCHAR(128)"` ++ TargetName string ++ TargetID int64 ++ Phase string ++ BeforeState string `xorm:"TEXT"` ++ DesiredState string `xorm:"TEXT"` ++ PostState string `xorm:"TEXT"` ++} ++ ++func (sourceOperationJournal) TableName() string { return "login_source_operation" } ++func init() { db.RegisterModel(new(sourceOperationJournal)) } ++ ++// SourceOperationResult contains only public outcome metadata. An authenticated ++// session/evidence producer must bind this result to its actual principal, ++// admitted source revision, exact parameters and current operation session. ++type SourceOperationResult struct { ++ OperationID string ++ Phase string ++ SourceID int64 ++} ++ ++// sourceOperationTx acquires a database-enforced lock before any source read. ++// SQLite's first write serializes every database writer, including stock admin ++// CRUD. PostgreSQL table locks exclude ordinary SQL source and user-link writes. ++// Privileged DDL, process/provider refresh and release writers are outside this ++// bounded primitive; they still require owner runtime/release exclusion. ++func sourceOperationTx(ctx context.Context, f func(context.Context) error) error { ++ if db.InTransaction(ctx) || setting.Database.LogSQL || (!setting.Database.Type.IsSQLite3() && !setting.Database.Type.IsPostgreSQL()) { ++ return ErrSourceOperationUnsupported ++ } ++ err := db.WithTx(db.WithSensitiveSQL(ctx), func(tx context.Context) error { ++ session, ok := db.GetEngine(tx).(*xorm.Session) ++ if !ok || session.Engine().Logger().IsShowSQL() { ++ return ErrSourceOperationUnsupported ++ } ++ if setting.Database.Type.IsPostgreSQL() { ++ if _, err := db.GetEngine(tx).Exec(`LOCK TABLE login_source_operation, login_source, "user", external_login_user IN EXCLUSIVE MODE`); err != nil { ++ return err ++ } ++ } else { ++ // Even with no matching row, UPDATE starts SQLite's write transaction. ++ if _, err := db.GetEngine(tx).Exec(`UPDATE login_source_operation SET phase = phase WHERE operation_id = ''`); err != nil { ++ return err ++ } ++ } ++ return f(tx) ++ }) ++ if err == nil || errors.Is(err, ErrSourceOperationConflict) || errors.Is(err, ErrSourceOperationUnsupported) || IsErrSourceInUse(err) { ++ return err ++ } ++ return ErrSourceOperationStorage ++} ++ ++func sourceInventory(ctx context.Context) ([]sourceOperationRow, error) { ++ rows := make([]sourceOperationRow, 0) ++ err := db.GetEngine(ctx).OrderBy("id").Find(&rows) ++ return rows, err ++} ++func encodeSourceInventory(rows []sourceOperationRow) string { ++ b, _ := json.Marshal(rows) ++ return string(b) ++} ++func decodeSourceInventory(s string) ([]sourceOperationRow, error) { ++ var rows []sourceOperationRow ++ if err := json.Unmarshal([]byte(s), &rows); err != nil { ++ return nil, ErrSourceOperationConflict ++ } ++ return rows, nil ++} ++func sourceJournal(ctx context.Context, operationID string) (*sourceOperationJournal, error) { ++ row := new(sourceOperationJournal) ++ found, err := db.GetEngine(ctx).ID(operationID).Get(row) ++ if err != nil { ++ return nil, err ++ } ++ if !found { ++ return nil, ErrSourceOperationConflict ++ } ++ return row, nil ++} ++func journalResult(j *sourceOperationJournal) SourceOperationResult { ++ return SourceOperationResult{OperationID: j.OperationID, Phase: j.Phase, SourceID: j.TargetID} ++} ++ ++// PrepareSourceOperation durably captures exact source identity and complete ++// original inventory before mutation. desired is private owner input, not an ++// authorization token. targetID=0 requires authoritative name absence. Existing ++// sources require both exact ID and name. Reuse of an operation ID is refused. ++func PrepareSourceOperation(ctx context.Context, operationID, caseID string, targetID int64, desired *Source) (SourceOperationResult, error) { ++ var result SourceOperationResult ++ if !operationIDPattern.MatchString(operationID) || !operationIDPattern.MatchString(caseID) || desired == nil || desired.Type != OAuth2 || desired.Name == "" || desired.Cfg == nil || desired.IsSyncEnabled || desired.ID != targetID { ++ return result, ErrSourceOperationConflict ++ } ++ cfg, err := desired.Cfg.ToDB() ++ if err != nil || len(cfg) > 64*1024 || !json.Valid(cfg) { ++ return result, ErrSourceOperationConflict ++ } ++ candidate := sourceOperationRow{ID: targetID, Type: OAuth2, Name: desired.Name, IsActive: desired.IsActive, Cfg: string(cfg)} ++ candidateBytes, _ := json.Marshal(candidate) ++ err = sourceOperationTx(ctx, func(tx context.Context) error { ++ // Bound confidential duplicate custody. Refuse rather than erase journals ++ // with pending recovery or silently expire terminal private snapshots. ++ count, err := db.GetEngine(tx).Count(new(sourceOperationJournal)) ++ if err != nil { ++ return err ++ } ++ if count >= 256 { ++ return ErrSourceOperationConflict ++ } ++ active, err := db.GetEngine(tx).Where("phase IN (?, ?, ?)", "prepared", "applied", "unchanged").Count(new(sourceOperationJournal)) ++ if err != nil { ++ return err ++ } ++ if active >= 64 { ++ return ErrSourceOperationConflict ++ } ++ found, err := db.GetEngine(tx).ID(operationID).Exist(new(sourceOperationJournal)) ++ if err != nil { ++ return err ++ } ++ if found { ++ return ErrSourceOperationConflict ++ } ++ shared, err := db.GetEngine(tx).Where("target_name = ? AND phase IN (?, ?, ?)", desired.Name, "prepared", "applied", "unchanged").Exist(new(sourceOperationJournal)) ++ if err != nil { ++ return err ++ } ++ if shared { ++ return ErrSourceOperationConflict ++ } ++ rows, err := sourceInventory(tx) ++ if err != nil { ++ return err ++ } ++ if len(encodeSourceInventory(rows)) > 1024*1024 { ++ return ErrSourceOperationConflict ++ } ++ matched := false ++ for _, row := range rows { ++ if row.Name == desired.Name || row.ID == targetID { ++ if targetID == 0 || row.ID != targetID || row.Name != desired.Name || row.Type != OAuth2 { ++ return ErrSourceOperationConflict ++ } ++ matched = true ++ } ++ } ++ if targetID != 0 && !matched { ++ return ErrSourceOperationConflict ++ } ++ j := &sourceOperationJournal{OperationID: operationID, CaseID: caseID, TargetName: desired.Name, TargetID: targetID, Phase: "prepared", BeforeState: encodeSourceInventory(rows), DesiredState: string(candidateBytes)} ++ if _, err := db.GetEngine(tx).Insert(j); err != nil { ++ return err ++ } ++ result = journalResult(j) ++ return nil ++ }) ++ if err != nil { ++ return SourceOperationResult{}, err ++ } ++ return result, nil ++} ++ ++// ApplySourceOperation atomically compares every original raw source row, ++// mutates exactly the target and persists confirmed post-state. A lost commit ++// acknowledgement is reconciled using the same operation ID, never a fresh ID. ++// No source registration/network call occurs inside the database transaction. ++func ApplySourceOperation(ctx context.Context, operationID, caseID string) (SourceOperationResult, error) { ++ var result SourceOperationResult ++ err := sourceOperationTx(ctx, func(tx context.Context) error { ++ j, err := sourceJournal(tx, operationID) ++ if err != nil { ++ return err ++ } ++ if j.CaseID != caseID { ++ return ErrSourceOperationConflict ++ } ++ rows, err := sourceInventory(tx) ++ if err != nil { ++ return err ++ } ++ if j.Phase == "applied" || j.Phase == "unchanged" { ++ if encodeSourceInventory(rows) != j.PostState { ++ return ErrSourceOperationConflict ++ } ++ result = journalResult(j) ++ return nil ++ } ++ if j.Phase != "prepared" || encodeSourceInventory(rows) != j.BeforeState { ++ return ErrSourceOperationConflict ++ } ++ var desired sourceOperationRow ++ if json.Unmarshal([]byte(j.DesiredState), &desired) != nil { ++ return ErrSourceOperationConflict ++ } ++ unchanged := false ++ for _, row := range rows { ++ if row.ID == j.TargetID { ++ desired.CreatedUnix = row.CreatedUnix ++ desired.UpdatedUnix = row.UpdatedUnix ++ unchanged = reflect.DeepEqual(row, desired) ++ } ++ } ++ if !unchanged { ++ desired.UpdatedUnix = timeutil.TimeStampNow() ++ if j.TargetID == 0 { ++ desired.CreatedUnix = desired.UpdatedUnix ++ if _, err := db.GetEngine(tx).NoAutoTime().Insert(&desired); err != nil { ++ return err ++ } ++ j.TargetID = desired.ID ++ } else { ++ n, err := db.GetEngine(tx).ID(j.TargetID).NoAutoTime().AllCols().Update(&desired) ++ if err != nil { ++ return err ++ } ++ if n != 1 { ++ return ErrSourceOperationConflict ++ } ++ } ++ } ++ post, err := sourceInventory(tx) ++ if err != nil { ++ return err ++ } ++ expected := append([]sourceOperationRow{}, rows...) ++ if !unchanged { ++ replaced := false ++ for i := range expected { ++ if expected[i].ID == desired.ID { ++ expected[i] = desired ++ replaced = true ++ } ++ } ++ if !replaced { ++ expected = append(expected, desired) ++ } ++ sort.Slice(expected, func(i, k int) bool { return expected[i].ID < expected[k].ID }) ++ } ++ if !reflect.DeepEqual(post, expected) { ++ return ErrSourceOperationConflict ++ } ++ j.PostState = encodeSourceInventory(post) ++ j.Phase = "applied" ++ if unchanged { ++ j.Phase = "unchanged" ++ } ++ if _, err := db.GetEngine(tx).ID(j.OperationID).AllCols().Update(j); err != nil { ++ return err ++ } ++ result = journalResult(j) ++ return nil ++ }) ++ if err != nil { ++ return SourceOperationResult{}, err ++ } ++ return result, nil ++} ++ ++// InverseSourceOperation requires fresh external inverse authority on EACH call. ++// It restores a preexisting source in place; only confirmed case creation can ++// delete. Any linked local/external account refuses deletion without alteration. ++func InverseSourceOperation(ctx context.Context, operationID, caseID string) (SourceOperationResult, error) { ++ var result SourceOperationResult ++ err := sourceOperationTx(ctx, func(tx context.Context) error { ++ j, err := sourceJournal(tx, operationID) ++ if err != nil { ++ return err ++ } ++ if j.CaseID != caseID { ++ return ErrSourceOperationConflict ++ } ++ rows, err := sourceInventory(tx) ++ if err != nil { ++ return err ++ } ++ if j.Phase == "reverted" || j.Phase == "cancelled" { ++ if encodeSourceInventory(rows) != j.BeforeState { ++ return ErrSourceOperationConflict ++ } ++ result = journalResult(j) ++ return nil ++ } ++ if j.Phase == "prepared" { ++ if encodeSourceInventory(rows) != j.BeforeState { ++ return ErrSourceOperationConflict ++ } ++ j.Phase = "cancelled" ++ } else { ++ if (j.Phase != "applied" && j.Phase != "unchanged") || encodeSourceInventory(rows) != j.PostState { ++ return ErrSourceOperationConflict ++ } ++ before, err := decodeSourceInventory(j.BeforeState) ++ if err != nil { ++ return err ++ } ++ var original *sourceOperationRow ++ for i := range before { ++ if before[i].ID == j.TargetID { ++ original = &before[i] ++ } ++ } ++ if original != nil { ++ if _, err := db.GetEngine(tx).ID(j.TargetID).NoAutoTime().AllCols().Update(original); err != nil { ++ return err ++ } ++ } else { ++ for _, table := range []struct{ name, column string }{{"user", "login_source"}, {"external_login_user", "login_source_id"}} { ++ count, err := db.GetEngine(tx).Table(table.name).Where(table.column+" = ?", j.TargetID).Count() ++ if err != nil { ++ return err ++ } ++ if count != 0 { ++ return ErrSourceInUse{ID: j.TargetID} ++ } ++ } ++ n, err := db.GetEngine(tx).ID(j.TargetID).Delete(new(sourceOperationRow)) ++ if err != nil { ++ return err ++ } ++ if n != 1 { ++ return ErrSourceOperationConflict ++ } ++ } ++ restored, err := sourceInventory(tx) ++ if err != nil { ++ return err ++ } ++ if encodeSourceInventory(restored) != j.BeforeState { ++ return ErrSourceOperationConflict ++ } ++ j.Phase = "reverted" ++ } ++ if _, err := db.GetEngine(tx).ID(j.OperationID).AllCols().Update(j); err != nil { ++ return err ++ } ++ result = journalResult(j) ++ return nil ++ }) ++ if err != nil { ++ return SourceOperationResult{}, err ++ } ++ return result, nil ++} ++ ++// ReconcileSourceOperation only checks committed journal/current equality. It ++// never infers that a prepared intent ran and never retries the mutation. The ++// separately authenticated runtime must call this after an ambiguous result. ++func ReconcileSourceOperation(ctx context.Context, operationID, caseID string) (SourceOperationResult, error) { ++ var result SourceOperationResult ++ err := sourceOperationTx(ctx, func(tx context.Context) error { ++ j, err := sourceJournal(tx, operationID) ++ if err != nil { ++ return err ++ } ++ if j.CaseID != caseID { ++ return ErrSourceOperationConflict ++ } ++ rows, err := sourceInventory(tx) ++ if err != nil { ++ return err ++ } ++ expected := j.BeforeState ++ switch j.Phase { ++ case "prepared", "reverted", "cancelled": ++ case "applied", "unchanged": ++ expected = j.PostState ++ default: ++ return ErrSourceOperationConflict ++ } ++ if encodeSourceInventory(rows) != expected { ++ return ErrSourceOperationConflict ++ } ++ result = journalResult(j) ++ return nil ++ }) ++ if err != nil { ++ return SourceOperationResult{}, err ++ } ++ return result, nil ++} +--- /dev/null ++++ b/models/auth/source_operation_internal_test.go +@@ -0,0 +1,87 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++package auth ++ ++import ( ++ "context" ++ "testing" ++ "time" ++ ++ "forgejo.org/models/db" ++ "xorm.io/xorm" ++) ++ ++func TestSourceOperationDatabaseWriterExclusion(t *testing.T) { ++ // Use DEFERRED transaction mode in the managed engine as well, so this ++ // test detects removal of the primitive's explicit first write. ++ previousContext := db.DefaultContext ++ previousEngine, ok := db.GetEngine(previousContext).(*xorm.Engine) ++ if !ok { ++ t.Fatal("missing actual fixture engine") ++ } ++ managed, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=deferred") ++ if err != nil { ++ t.Fatal(err) ++ } ++ db.SetDefaultEngine(context.Background(), managed) ++ defer func() { db.SetDefaultEngine(previousContext, previousEngine); managed.Close() }() ++ // A second actual connection executes uncooperative raw SQL, so this checks ++ // database exclusion rather than an advisory-lock convention. ++ raw, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=deferred") ++ if err != nil { ++ t.Fatal(err) ++ } ++ defer raw.Close() ++ locked := make(chan struct{}) ++ release := make(chan struct{}) ++ done := make(chan error, 1) ++ go func() { ++ done <- sourceOperationTx(db.DefaultContext, func(ctx context.Context) error { close(locked); <-release; return nil }) ++ }() ++ select { ++ case <-locked: ++ case err := <-done: ++ t.Fatalf("lock failed: %v", err) ++ case <-time.After(5 * time.Second): ++ t.Fatal("lock timed out") ++ } ++ writeDone := make(chan error, 1) ++ go func() { _, err := raw.Exec("UPDATE login_source SET name = name WHERE id = -123"); writeDone <- err }() ++ select { ++ case err := <-writeDone: ++ close(release) ++ <-done ++ t.Fatalf("uncooperative write escaped exclusion: %v", err) ++ case <-time.After(100 * time.Millisecond): ++ } ++ close(release) ++ select { ++ case err := <-done: ++ if err != nil { ++ t.Fatal(err) ++ } ++ case <-time.After(5 * time.Second): ++ t.Fatal("transaction did not finish") ++ } ++ select { ++ case err := <-writeDone: ++ if err != nil { ++ t.Fatal(err) ++ } ++ case <-time.After(5 * time.Second): ++ t.Fatal("writer did not resume") ++ } ++} ++func TestSourceOperationRefusesActualXORMArgumentLogging(t *testing.T) { ++ engine, ok := db.GetEngine(db.DefaultContext).(*xorm.Engine) ++ if !ok { ++ t.Fatal("missing actual engine") ++ } ++ engine.ShowSQL(true) ++ defer engine.ShowSQL(false) ++ called := false ++ err := sourceOperationTx(db.DefaultContext, func(context.Context) error { called = true; return nil }) ++ if err != ErrSourceOperationUnsupported || called { ++ t.Fatal("actual SQL argument logger did not fail closed") ++ } ++} +--- /dev/null ++++ b/models/auth/source_operation_process_test.go +@@ -0,0 +1,97 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++package auth_test ++ ++import ( ++ "context" ++ "os" ++ "os/exec" ++ "path/filepath" ++ "strings" ++ "testing" ++ ++ auth "forgejo.org/models/auth" ++ "forgejo.org/models/db" ++ oauth2 "forgejo.org/services/auth/source/oauth2" ++ ++ "github.com/stretchr/testify/require" ++ "xorm.io/xorm" ++ "xorm.io/xorm/contexts" ++ "xorm.io/xorm/names" ++) ++ ++type operationCrashAfterSourceInsert struct{} ++ ++func (operationCrashAfterSourceInsert) BeforeProcess(c *contexts.ContextHook) (context.Context, error) { ++ return c.Ctx, nil ++} ++func (operationCrashAfterSourceInsert) AfterProcess(c *contexts.ContextHook) error { ++ if c.Err == nil && strings.Contains(c.SQL, "INSERT INTO") && strings.Contains(c.SQL, "login_source") && !strings.Contains(c.SQL, "login_source_operation") { ++ // Process death after the real INSERT, before actual ApplySourceOperation's ++ // post-read/journal update/commit. No artificial operation is substituted. ++ os.Exit(73) ++ } ++ return nil ++} ++func TestSourceOperationProcessRecovery(t *testing.T) { ++ if step := os.Getenv("SOURCE_OPERATION_CHILD_STEP"); step != "" { ++ e, err := xorm.NewEngine("sqlite3", os.Getenv("SOURCE_OPERATION_CHILD_DB")+"?_txlock=deferred") ++ require.NoError(t, err) ++ e.SetMapper(names.GonicMapper{}) ++ db.SetDefaultEngine(context.Background(), e) ++ require.NoError(t, db.SyncAllTables()) ++ auth.RegisterTypeConfig(auth.OAuth2, new(oauth2.Source)) ++ ctx := db.DefaultContext ++ switch step { ++ case "prepare": ++ _, err = auth.PrepareSourceOperation(ctx, "operation-process-recovery", "case-process-recovery", 0, operationSource()) ++ require.NoError(t, err) ++ case "crash": ++ e.AddHook(operationCrashAfterSourceInsert{}) ++ _, err = auth.ApplySourceOperation(ctx, "operation-process-recovery", "case-process-recovery") ++ require.NoError(t, err) ++ t.Fatal("real insert did not reach crash hook") ++ case "recover-prepared": ++ r, err := auth.ReconcileSourceOperation(ctx, "operation-process-recovery", "case-process-recovery") ++ require.NoError(t, err) ++ require.Equal(t, "prepared", r.Phase) ++ n, err := db.GetEngine(ctx).Table("login_source").Count() ++ require.NoError(t, err) ++ require.Zero(t, n) ++ _, err = auth.ApplySourceOperation(ctx, "operation-process-recovery", "case-process-recovery") ++ require.NoError(t, err) ++ case "recover-applied": ++ r, err := auth.ReconcileSourceOperation(ctx, "operation-process-recovery", "case-process-recovery") ++ require.NoError(t, err) ++ require.Equal(t, "applied", r.Phase) ++ _, err = auth.InverseSourceOperation(ctx, "operation-process-recovery", "case-process-recovery") ++ require.NoError(t, err) ++ case "recover-inverse": ++ r, err := auth.ReconcileSourceOperation(ctx, "operation-process-recovery", "case-process-recovery") ++ require.NoError(t, err) ++ require.Equal(t, "reverted", r.Phase) ++ n, err := db.GetEngine(ctx).Table("login_source").Count() ++ require.NoError(t, err) ++ require.Zero(t, n) ++ default: ++ t.Fatal("unknown synthetic child step") ++ } ++ require.NoError(t, e.Close()) ++ return ++ } ++ exe, err := os.Executable() ++ require.NoError(t, err) ++ path := filepath.Join(t.TempDir(), "owner-private.sqlite") ++ for _, step := range []string{"prepare", "crash", "recover-prepared", "recover-applied", "recover-inverse"} { ++ child := exec.Command(exe, "-test.run=^TestSourceOperationProcessRecovery$", "-test.v") ++ child.Env = append(os.Environ(), "SOURCE_OPERATION_CHILD_STEP="+step, "SOURCE_OPERATION_CHILD_DB="+path) ++ output, err := child.CombinedOutput() ++ if step == "crash" { ++ exit, ok := err.(*exec.ExitError) ++ require.True(t, ok, string(output)) ++ require.Equal(t, 73, exit.ExitCode(), string(output)) ++ } else { ++ require.NoError(t, err, string(output)) ++ } ++ } ++} +--- /dev/null ++++ b/models/auth/source_operation_test.go +@@ -0,0 +1,235 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++package auth_test ++ ++import ( ++ "context" ++ "encoding/json" ++ "fmt" ++ "testing" ++ ++ auth "forgejo.org/models/auth" ++ "forgejo.org/models/db" ++ "forgejo.org/models/unittest" ++ "forgejo.org/modules/setting" ++ oauth2 "forgejo.org/services/auth/source/oauth2" ++ ++ "github.com/stretchr/testify/require" ++) ++ ++func operationDB(t *testing.T) context.Context { ++ t.Helper() ++ require.NoError(t, unittest.PrepareTestDatabase()) ++ _, err := db.GetEngine(db.DefaultContext).Exec("DELETE FROM login_source_operation") ++ require.NoError(t, err) ++ auth.RegisterTypeConfig(auth.OAuth2, new(oauth2.Source)) ++ return db.DefaultContext ++} ++func operationSource() *auth.Source { ++ return &auth.Source{Type: auth.OAuth2, Name: "operation-test", IsActive: false, Cfg: &oauth2.Source{Provider: "openidConnect", ClientID: "synthetic-client", ClientSecret: "synthetic-private-original", RequiredClaimName: "groups", RequiredClaimValues: []string{"g1", "g2", "g3"}, Scopes: []string{"openid", "profile", "groups"}}} ++} ++func operationRows(t *testing.T, ctx context.Context) string { ++ t.Helper() ++ rows, err := db.GetEngine(ctx).Query("SELECT * FROM login_source ORDER BY id") ++ require.NoError(t, err) ++ b, err := json.Marshal(rows) ++ require.NoError(t, err) ++ return string(b) ++} ++func TestSourceOperationCreateAndInverse(t *testing.T) { ++ ctx := operationDB(t) ++ before := operationRows(t, ctx) ++ r, err := auth.PrepareSourceOperation(ctx, "operation-create", "case-create", 0, operationSource()) ++ require.NoError(t, err) ++ require.Equal(t, "prepared", r.Phase) ++ require.Equal(t, before, operationRows(t, ctx)) ++ r, err = auth.ApplySourceOperation(ctx, "operation-create", "case-create") ++ require.NoError(t, err) ++ require.Equal(t, "applied", r.Phase) ++ require.Positive(t, r.SourceID) ++ id := r.SourceID ++ post := operationRows(t, ctx) ++ r, err = auth.ApplySourceOperation(ctx, "operation-create", "case-create") ++ require.NoError(t, err) ++ require.Equal(t, id, r.SourceID) ++ require.Equal(t, post, operationRows(t, ctx)) ++ _, err = auth.InverseSourceOperation(ctx, "operation-create", "wrong-case") ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++ r, err = auth.InverseSourceOperation(ctx, "operation-create", "case-create") ++ require.NoError(t, err) ++ require.Equal(t, "reverted", r.Phase) ++ require.Equal(t, before, operationRows(t, ctx)) ++ _, err = auth.InverseSourceOperation(ctx, "operation-create", "case-create") ++ require.NoError(t, err) ++ _, err = auth.ApplySourceOperation(ctx, "operation-create", "case-create") ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++} ++func TestSourceOperationRestoresExactRawPreexisting(t *testing.T) { ++ ctx := operationDB(t) ++ s := operationSource() ++ require.NoError(t, auth.CreateSource(ctx, s)) ++ // The old/unknown field must survive restoration byte for byte, including the ++ // private synthetic secret. A typed OAuth2 decoder would silently lose it. ++ raw := `{"Provider":"openidConnect","ClientID":"synthetic-client","ClientSecret":"synthetic-private-original","FutureGuard":{"x":true}}` ++ _, err := db.GetEngine(ctx).Exec("UPDATE login_source SET cfg = ? WHERE id = ?", raw, s.ID) ++ require.NoError(t, err) ++ before := operationRows(t, ctx) ++ s.Cfg.(*oauth2.Source).ClientSecret = "synthetic-private-new" ++ _, err = auth.PrepareSourceOperation(ctx, "operation-restore", "case-restore", s.ID, s) ++ require.NoError(t, err) ++ _, err = auth.ApplySourceOperation(ctx, "operation-restore", "case-restore") ++ require.NoError(t, err) ++ _, err = auth.InverseSourceOperation(ctx, "operation-restore", "case-restore") ++ require.NoError(t, err) ++ require.Equal(t, before, operationRows(t, ctx)) ++ source, err := auth.GetSourceByID(ctx, s.ID) ++ require.NoError(t, err) ++ require.Equal(t, s.ID, source.ID) ++} ++func TestSourceOperationUnchangedNeverDeletesPreexisting(t *testing.T) { ++ ctx := operationDB(t) ++ s := operationSource() ++ require.NoError(t, auth.CreateSource(ctx, s)) ++ before := operationRows(t, ctx) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-unchanged", "case-unchanged", s.ID, s) ++ require.NoError(t, err) ++ r, err := auth.ApplySourceOperation(ctx, "operation-unchanged", "case-unchanged") ++ require.NoError(t, err) ++ require.Equal(t, "unchanged", r.Phase) ++ _, err = auth.InverseSourceOperation(ctx, "operation-unchanged", "case-unchanged") ++ require.NoError(t, err) ++ require.Equal(t, before, operationRows(t, ctx)) ++} ++func TestSourceOperationPrivateDriftRefuses(t *testing.T) { ++ for _, stage := range []string{"before-apply", "before-inverse"} { ++ t.Run(stage, func(t *testing.T) { ++ ctx := operationDB(t) ++ s := operationSource() ++ require.NoError(t, auth.CreateSource(ctx, s)) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-private-drift", "case-private-drift", s.ID, s) ++ require.NoError(t, err) ++ if stage == "before-inverse" { ++ _, err = auth.ApplySourceOperation(ctx, "operation-private-drift", "case-private-drift") ++ require.NoError(t, err) ++ } ++ s.Cfg.(*oauth2.Source).ClientSecret = "synthetic-private-drift" ++ require.NoError(t, auth.UpdateSource(ctx, s)) ++ drift := operationRows(t, ctx) ++ if stage == "before-apply" { ++ _, err = auth.ApplySourceOperation(ctx, "operation-private-drift", "case-private-drift") ++ } else { ++ _, err = auth.InverseSourceOperation(ctx, "operation-private-drift", "case-private-drift") ++ } ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++ require.NotContains(t, err.Error(), "synthetic-private") ++ require.Equal(t, drift, operationRows(t, ctx)) ++ }) ++ } ++} ++func TestSourceOperationStockCRUDDriftRefuses(t *testing.T) { ++ ctx := operationDB(t) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-other-writer", "case-other-writer", 0, operationSource()) ++ require.NoError(t, err) ++ other := operationSource() ++ other.Name = "unrelated-source" ++ require.NoError(t, auth.CreateSource(ctx, other)) ++ drift := operationRows(t, ctx) ++ _, err = auth.ApplySourceOperation(ctx, "operation-other-writer", "case-other-writer") ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++ require.Equal(t, drift, operationRows(t, ctx)) ++} ++func TestSourceOperationLinkedSourceRefusesDeletion(t *testing.T) { ++ for _, kind := range []string{"user", "external"} { ++ t.Run(kind, func(t *testing.T) { ++ ctx := operationDB(t) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-linked", "case-linked", 0, operationSource()) ++ require.NoError(t, err) ++ r, err := auth.ApplySourceOperation(ctx, "operation-linked", "case-linked") ++ require.NoError(t, err) ++ if kind == "user" { ++ _, err = db.GetEngine(ctx).Exec("UPDATE `user` SET login_source = ? WHERE id = 1", r.SourceID) ++ } else { ++ _, err = db.GetEngine(ctx).Exec("INSERT INTO external_login_user (external_id, user_id, login_source_id) VALUES (?, ?, ?)", "synthetic-external", 1, r.SourceID) ++ } ++ require.NoError(t, err) ++ before := operationRows(t, ctx) ++ _, err = auth.InverseSourceOperation(ctx, "operation-linked", "case-linked") ++ require.True(t, auth.IsErrSourceInUse(err)) ++ require.Equal(t, before, operationRows(t, ctx)) ++ if kind == "user" { ++ rows, e := db.GetEngine(ctx).Query("SELECT login_source FROM `user` WHERE id = 1") ++ require.NoError(t, e) ++ require.NotEqual(t, []byte("0"), rows[0]["login_source"]) ++ } else { ++ n, e := db.GetEngine(ctx).Table("external_login_user").Count() ++ require.NoError(t, e) ++ require.EqualValues(t, 1, n) ++ } ++ }) ++ } ++} ++func TestSourceOperationPreparedCancellationAndIDReuse(t *testing.T) { ++ ctx := operationDB(t) ++ before := operationRows(t, ctx) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-cancelled", "case-cancelled", 0, operationSource()) ++ require.NoError(t, err) ++ _, err = auth.PrepareSourceOperation(ctx, "operation-cancelled", "case-cancelled", 0, operationSource()) ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++ r, err := auth.InverseSourceOperation(ctx, "operation-cancelled", "case-cancelled") ++ require.NoError(t, err) ++ require.Equal(t, "cancelled", r.Phase) ++ require.Equal(t, before, operationRows(t, ctx)) ++} ++func TestSourceOperationRejectsUnsafeRuntime(t *testing.T) { ++ ctx := operationDB(t) ++ setting.Database.LogSQL = true ++ t.Cleanup(func() { setting.Database.LogSQL = false }) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-no-logging", "case-no-logging", 0, operationSource()) ++ require.ErrorIs(t, err, auth.ErrSourceOperationUnsupported) ++ setting.Database.LogSQL = false ++ err = db.WithTx(ctx, func(tx context.Context) error { ++ _, err := auth.PrepareSourceOperation(tx, "operation-nested", "case-nested", 0, operationSource()) ++ return err ++ }) ++ require.ErrorIs(t, err, auth.ErrSourceOperationUnsupported) ++} ++func TestSourceOperationRefusesSharedManagedSource(t *testing.T) { ++ ctx := operationDB(t) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-first-case", "case-first-case", 0, operationSource()) ++ require.NoError(t, err) ++ r, err := auth.ApplySourceOperation(ctx, "operation-first-case", "case-first-case") ++ require.NoError(t, err) ++ shared := operationSource() ++ shared.ID = r.SourceID ++ _, err = auth.PrepareSourceOperation(ctx, "operation-second-case", "case-second-case", r.SourceID, shared) ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++} ++func TestSourceOperationBoundsPrivateJournalCustody(t *testing.T) { ++ ctx := operationDB(t) ++ // A full unresolved-journal budget refuses new preparation, without deleting ++ // any intent or replacing private recovery data with an expiry assumption. ++ for i := 0; i < 64; i++ { ++ _, err := db.GetEngine(ctx).Exec("INSERT INTO login_source_operation (operation_id, case_id, target_name, phase) VALUES (?, ?, ?, ?)", fmt.Sprintf("bounded-operation-%03d", i), "bounded-case", fmt.Sprintf("bounded-target-%03d", i), "prepared") ++ require.NoError(t, err) ++ } ++ _, err := auth.PrepareSourceOperation(ctx, "operation-budget-full", "case-budget-full", 0, operationSource()) ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++ n, err := db.GetEngine(ctx).Table("login_source_operation").Count() ++ require.NoError(t, err) ++ require.EqualValues(t, 64, n) ++} ++func TestSourceOperationRequiresExactPostState(t *testing.T) { ++ ctx := operationDB(t) ++ before := operationRows(t, ctx) ++ _, err := auth.PrepareSourceOperation(ctx, "operation-post-exact", "case-post-exact", 0, operationSource()) ++ require.NoError(t, err) ++ _, err = db.GetEngine(ctx).Exec("CREATE TRIGGER source_operation_test_drift AFTER INSERT ON login_source BEGIN UPDATE login_source SET name = 'unexpected-rewrite' WHERE id = NEW.id; END") ++ require.NoError(t, err) ++ defer db.GetEngine(ctx).Exec("DROP TRIGGER source_operation_test_drift") ++ _, err = auth.ApplySourceOperation(ctx, "operation-post-exact", "case-post-exact") ++ require.ErrorIs(t, err, auth.ErrSourceOperationConflict) ++ require.Equal(t, before, operationRows(t, ctx)) ++ r, err := auth.ReconcileSourceOperation(ctx, "operation-post-exact", "case-post-exact") ++ require.NoError(t, err) ++ require.Equal(t, "prepared", r.Phase) ++} +--- a/models/db/context.go ++++ b/models/db/context.go +@@ -72,6 +72,12 @@ + // GetEngine will get a db Engine from this context or return an Engine restricted to this context + func GetEngine(ctx context.Context) Engine { + if e := getEngine(ctx); e != nil { ++ // A private-query marker must reach XORM's real query hooks, including ++ // inside an existing engine/transaction context. Wrapping the Go ++ // context alone does not change XORM's stored session context. ++ if isSensitiveSQL(ctx) { ++ return e.Context(ctx) ++ } + return e + } + return x.Context(ctx) +--- a/models/db/engine.go ++++ b/models/db/engine.go +@@ -330,8 +330,12 @@ + func (TracingHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) { + ctx, task := trace.NewTask(c.Ctx, "sql") + ctx = context.WithValue(ctx, sqlTask{}, task) +- trace.Log(ctx, "query", c.SQL) +- trace.Logf(ctx, "args", "%v", c.Args) ++ if isSensitiveSQL(c.Ctx) { ++ trace.Log(ctx, "query", "[owner-confined query]") ++ } else { ++ trace.Log(ctx, "query", c.SQL) ++ trace.Logf(ctx, "args", "%v", c.Args) ++ } + return ctx, nil + } + +@@ -353,7 +357,11 @@ + + func (h *SlowQueryHook) AfterProcess(c *contexts.ContextHook) error { + if c.ExecuteTime >= h.Treshold { +- h.Logger.Log(8, log.WARN, "[Slow SQL Query] %s %v - %v", c.SQL, c.Args, c.ExecuteTime) ++ if isSensitiveSQL(c.Ctx) { ++ h.Logger.Log(8, log.WARN, "[Slow SQL Query] [owner-confined query] - %v", c.ExecuteTime) ++ } else { ++ h.Logger.Log(8, log.WARN, "[Slow SQL Query] %s %v - %v", c.SQL, c.Args, c.ExecuteTime) ++ } + } + return nil + } +@@ -370,7 +378,11 @@ + + func (h *ErrorQueryHook) AfterProcess(c *contexts.ContextHook) error { + if c.Err != nil && !errors.Is(c.Err, context.Canceled) { +- h.Logger.Log(8, log.ERROR, "[Error SQL Query] %s %v - %v", c.SQL, c.Args, c.Err) +- } +- return nil +-} ++ if isSensitiveSQL(c.Ctx) { ++ h.Logger.Log(8, log.ERROR, "[Error SQL Query] [owner-confined query]") ++ } else { ++ h.Logger.Log(8, log.ERROR, "[Error SQL Query] %s %v - %v", c.SQL, c.Args, c.Err) ++ } ++ } ++ return nil ++} +--- /dev/null ++++ b/models/db/sensitive_sql.go +@@ -0,0 +1,47 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++package db ++ ++import ( ++ "context" ++ "forgejo.org/modules/setting" ++ "xorm.io/xorm" ++) ++ ++type sensitiveSQLKey struct{} ++ ++// WithSensitiveSQL suppresses argument, statement and driver-error disclosure ++// in the application's query hooks. The caller must separately refuse raw XORM ++// SQL logging; custom driver/server auditing remains an owner custody concern. ++func WithSensitiveSQL(ctx context.Context) context.Context { ++ return context.WithValue(ctx, sensitiveSQLKey{}, true) ++} ++func isSensitiveSQL(ctx context.Context) bool { ++ sensitive, _ := ctx.Value(sensitiveSQLKey{}).(bool) ++ return sensitive ++} ++ ++// SQLLoggingEnabled checks the underlying engine without changing the context or ++// assuming that a sensitive context still exposes an Engine rather than Session. ++// Unknown/uninitialized backends refuse, and query redaction never permits raw ++// XORM logging. It neither creates a transaction nor closes an existing one. ++func SQLLoggingEnabled(ctx context.Context) bool { ++ if setting.Database.LogSQL { ++ return true ++ } ++ engine := getEngine(ctx) ++ if engine == nil { ++ if x == nil { ++ return true ++ } ++ engine = x ++ } ++ switch current := engine.(type) { ++ case *xorm.Engine: ++ return current == nil || current.Logger() == nil || current.Logger().IsShowSQL() ++ case *xorm.Session: ++ return current == nil || current.Engine() == nil || current.Engine().Logger() == nil || current.Engine().Logger().IsShowSQL() ++ default: ++ return true ++ } ++} +--- /dev/null ++++ b/models/db/sensitive_sql_logging_test.go +@@ -0,0 +1,41 @@ ++package db ++ ++import ( ++ "context" ++ "testing" ++ ++ "forgejo.org/modules/setting" ++ "xorm.io/xorm" ++) ++ ++func TestSensitiveSQLLoggingChecksUnderlyingEngine(t *testing.T) { ++ engine, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared") ++ if err != nil { ++ t.Fatal(err) ++ } ++ defer engine.Close() ++ engine.SetLogger(NewXORMLogger(false)) ++ session := engine.NewSession() ++ defer session.Close() ++ previous := setting.Database.LogSQL ++ defer func() { setting.Database.LogSQL = previous }() ++ for name, backend := range map[string]Engine{"engine": engine, "session": session} { ++ t.Run(name, func(t *testing.T) { ++ ctx := WithSensitiveSQL(newContext(context.Background(), backend, false)) ++ setting.Database.LogSQL = false ++ engine.ShowSQL(false) ++ if SQLLoggingEnabled(ctx) { ++ t.Fatal("private context with disabled actual SQL logger refused") ++ } ++ engine.ShowSQL(true) ++ if !SQLLoggingEnabled(ctx) { ++ t.Fatal("actual raw SQL logger escaped refusal") ++ } ++ engine.ShowSQL(false) ++ setting.Database.LogSQL = true ++ if !SQLLoggingEnabled(ctx) { ++ t.Fatal("configured raw SQL logger escaped refusal") ++ } ++ }) ++ } ++} +--- /dev/null ++++ b/models/db/sensitive_sql_test.go +@@ -0,0 +1,103 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++package db ++ ++import ( ++ "bytes" ++ "context" ++ "errors" ++ "fmt" ++ "runtime/trace" ++ "strings" ++ "testing" ++ "time" ++ ++ "forgejo.org/modules/log" ++ "xorm.io/xorm" ++ "xorm.io/xorm/contexts" ++) ++ ++type sensitiveSQLLog struct { ++ log.Logger ++ entries []string ++} ++ ++func (l *sensitiveSQLLog) Log(_ int, _ log.Level, f string, v ...any) { ++ l.entries = append(l.entries, fmt.Sprintf(f, v...)) ++} ++func TestSensitiveSQLHooks(t *testing.T) { ++ const secret = "synthetic-query-private-sentinel" ++ for _, sensitive := range []bool{false, true} { ++ ctx := context.Background() ++ if sensitive { ++ ctx = WithSensitiveSQL(ctx) ++ } ++ h := &contexts.ContextHook{Ctx: ctx, SQL: "SELECT '" + secret + "'", Args: []any{secret}, Err: errors.New(secret), ExecuteTime: time.Second} ++ logger := new(sensitiveSQLLog) ++ if err := (&SlowQueryHook{Logger: logger}).AfterProcess(h); err != nil { ++ t.Fatal(err) ++ } ++ if err := (&ErrorQueryHook{Logger: logger}).AfterProcess(h); err != nil { ++ t.Fatal(err) ++ } ++ found := strings.Contains(strings.Join(logger.entries, "\n"), secret) ++ if found == sensitive { ++ t.Fatal("query hook disclosure/redaction mismatch") ++ } ++ var out bytes.Buffer ++ if err := trace.Start(&out); err != nil { ++ t.Fatal(err) ++ } ++ next, err := (TracingHook{}).BeforeProcess(h) ++ if err != nil { ++ trace.Stop() ++ t.Fatal(err) ++ } ++ h.Ctx = next ++ err = (TracingHook{}).AfterProcess(h) ++ trace.Stop() ++ if err != nil { ++ t.Fatal(err) ++ } ++ if bytes.Contains(out.Bytes(), []byte(secret)) == sensitive { ++ t.Fatal("trace disclosure/redaction mismatch") ++ } ++ } ++} ++ ++func TestSensitiveSQLActualContextPropagation(t *testing.T) { ++ engine, ok := GetEngine(DefaultContext).(*xorm.Engine) ++ if !ok { ++ t.Fatal("missing actual fixture engine") ++ } ++ logger := new(sensitiveSQLLog) ++ engine.AddHook(&SlowQueryHook{Logger: logger}) ++ engine.AddHook(&ErrorQueryHook{Logger: logger}) ++ engine.AddHook(TracingHook{}) ++ const secret = "synthetic-actual-xorm-private-sentinel" ++ for _, sensitive := range []bool{false, true} { ++ logger.entries = nil ++ ctx := context.Context(DefaultContext) ++ if sensitive { ++ ctx = WithSensitiveSQL(ctx) ++ } ++ var out bytes.Buffer ++ if err := trace.Start(&out); err != nil { ++ t.Fatal(err) ++ } ++ _, err := GetEngine(ctx).Exec("SELECT missing_synthetic_function(?)", secret) ++ trace.Stop() ++ if err == nil { ++ t.Fatal("expected actual SQLite function refusal") ++ } ++ if len(logger.entries) < 2 { ++ t.Fatal("actual query hooks did not execute") ++ } ++ if strings.Contains(strings.Join(logger.entries, "\n"), secret) == sensitive { ++ t.Fatal("actual XORM query context did not preserve redaction") ++ } ++ if bytes.Contains(out.Bytes(), []byte(secret)) == sensitive { ++ t.Fatal("actual XORM trace context did not preserve redaction") ++ } ++ } ++} +--- a/routers/web/admin/auths.go ++++ b/routers/web/admin/auths.go +@@ -322,6 +322,13 @@ + ctx.Data["Source"] = source + ctx.Data["HasTLS"] = source.HasTLS() + ++ // The legacy form has no representation for the opt-in current-UserInfo gate. ++ // Refuse rather than silently dropping it during source reconstruction. ++ if current, ok := source.Cfg.(*oauth2.Source); ok && current.RequiredClaimValues != nil { ++ ctx.RenderWithErr("This OAuth source uses required-claim-values; update it through the reviewed CLI.", tplAuthEdit, form) ++ return ++ } ++ + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplAuthEdit) + return +--- a/routers/web/auth/oauth.go ++++ b/routers/web/auth/oauth.go +@@ -1427,7 +1427,13 @@ + return goth.User{}, err + } + +- if oauth2Source.RequiredClaimName != "" { ++ if oauth2Source.RequiredClaimValues != nil { ++ // The exact callback has already authenticated and enforced the current ++ // Access Engine application.access decision. Group policy lives there. ++ if oauth2Source.Provider != "openidConnect" { ++ return goth.User{}, user_model.ErrUserProhibitLogin{Name: gothUser.UserID} ++ } ++ } else if oauth2Source.RequiredClaimName != "" { + claimInterface, has := gothUser.RawData[oauth2Source.RequiredClaimName] + if !has { + return goth.User{}, user_model.ErrUserProhibitLogin{Name: gothUser.UserID} +--- /dev/null ++++ b/services/auth/source/oauth2/access_engine.go +@@ -0,0 +1,224 @@ ++// 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"` ++ TenantSourceClaim string `json:"tenant_source_claim"` ++ MaxAuthenticationAge string `json:"max_authentication_age"` ++ 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 ++ TenantSource string ++ AssuranceData map[string]any ++ AuthenticatedAt time.Time ++ 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) ++ authAge, authErr := time.ParseDuration(a.MaxAuthenticationAge) ++ if e != nil || authErr != nil || authAge <= 0 || age <= 0 || a.TenantSourceClaim == "" || 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 authorizedParty, present := claims["azp"]; present { ++ if azp, ok := authorizedParty.(string); !ok || azp != a.Audience { ++ return out, errApplicationDecision ++ } ++ } else if len(aud) > 1 { ++ 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 ++ } ++ tenantSource, ok := value(a.TenantSourceClaim) ++ if !ok || (tenantSource != "directory" && tenantSource != "registration" && tenantSource != "default") { ++ return out, errApplicationDecision ++ } ++ assurance, assuranceData, authenticatedAt, authenticationEnd, err := verifiedKeyCapeAssurance(claims[a.AssuranceClaim], issued.Time, now, authAge) ++ if err != nil { ++ return out, errApplicationDecision ++ } ++ validUntil := end.Time ++ for _, bound := range []time.Time{issued.Time.Add(age), authenticationEnd} { ++ if bound.Before(validUntil) { ++ validUntil = bound ++ } ++ } ++ if !now.Before(validUntil) { ++ return out, errApplicationDecision ++ } ++ return VerifiedApplicationIdentity{Issuer: a.Issuer, Subject: subject, Tenant: tenant, PrincipalType: api.SubjectType(principal), Assurance: assurance, TenantSource: tenantSource, AssuranceData: assuranceData, AuthenticatedAt: authenticatedAt, NotAfter: validUntil}, 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_assurance_claim": identity.AssuranceData, "identity_authenticated_at": identity.AuthenticatedAt.UTC().Format(time.RFC3339Nano), "identity_tenant_source": identity.TenantSource, "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 ++} +--- /dev/null ++++ b/services/auth/source/oauth2/access_engine_assurance.go +@@ -0,0 +1,54 @@ ++package oauth2 ++ ++import ( ++ "encoding/json" ++ "time" ++) ++ ++// Validate the actual IAM v0.3 object only after issuer JOSE verification. These ++// are identity facts, not an access verdict: aal1/service facts still reach the ++// PDP, which owns the application's assurance and principal policy. Preserve the ++// full object and its integer timestamp in the signed decision request. ++func verifiedKeyCapeAssurance(raw any, issued, now time.Time, maxAge time.Duration) (string, map[string]any, time.Time, time.Time, error) { ++ refuse := func() (string, map[string]any, time.Time, time.Time, error) { ++ return "", nil, time.Time{}, time.Time{}, errApplicationDecision ++ } ++ claim, ok := raw.(map[string]any) ++ if !ok || len(claim) != 5 { ++ return refuse() ++ } ++ level, ok := claim["level"].(string) ++ if !ok || (level != "aal1" && level != "aal2" && level != "service") { ++ return refuse() ++ } ++ mfa, ok := claim["mfa"].(bool) ++ if !ok || mfa != (level == "aal2") || claim["source"] != "key-cape" { ++ return refuse() ++ } ++ methods, ok := claim["methods"].([]any) ++ if !ok || len(methods) == 0 { ++ return refuse() ++ } ++ seen := map[string]bool{} ++ for _, method := range methods { ++ value, ok := method.(string) ++ if !ok || !validClaimLiteral(value) || seen[value] { ++ return refuse() ++ } ++ seen[value] = true ++ } ++ number, ok := claim["at"].(json.Number) ++ if !ok { ++ return refuse() ++ } ++ seconds, err := number.Int64() ++ if err != nil || seconds <= 0 || seconds > issued.Unix() || seconds > now.Unix() { ++ return refuse() ++ } ++ authenticated := time.Unix(seconds, 0).UTC() ++ end := authenticated.Add(maxAge) ++ if maxAge <= 0 || !now.Before(end) { ++ return refuse() ++ } ++ return level, claim, authenticated, end, nil ++} +--- /dev/null ++++ b/services/auth/source/oauth2/access_engine_assurance_test.go +@@ -0,0 +1,75 @@ ++package oauth2 ++ ++import ( ++ "encoding/json" ++ "testing" ++ "time" ++) ++ ++func TestAccessEngineKeyCapeAssuranceRefusals(t *testing.T) { ++ cases := map[string]func(map[string]any, time.Time){ ++ "stale-authentication": func(c map[string]any, now time.Time) { c["at"] = now.Add(-10 * time.Minute).Unix() }, ++ "future-authentication": func(c map[string]any, now time.Time) { c["at"] = now.Add(time.Minute).Unix() }, ++ "missing-at": func(c map[string]any, _ time.Time) { delete(c, "at") }, ++ "string-at": func(c map[string]any, _ time.Time) { c["at"] = "recent" }, ++ "fractional-at": func(c map[string]any, now time.Time) { c["at"] = float64(now.Unix()) - 1.5 }, ++ "integer-mfa": func(c map[string]any, _ time.Time) { c["mfa"] = 1 }, ++ "inconsistent-mfa": func(c map[string]any, _ time.Time) { c["mfa"] = false }, ++ "wrong-source": func(c map[string]any, _ time.Time) { c["source"] = "userinfo" }, ++ "wrong-level": func(c map[string]any, _ time.Time) { c["level"] = "verified" }, ++ "object-methods": func(c map[string]any, _ time.Time) { c["methods"] = map[string]any{"pwd": true} }, ++ "empty-methods": func(c map[string]any, _ time.Time) { c["methods"] = []string{} }, ++ "mixed-methods": func(c map[string]any, _ time.Time) { c["methods"] = []any{"pwd", 1} }, ++ "duplicate-methods": func(c map[string]any, _ time.Time) { c["methods"] = []string{"pwd", "pwd"} }, ++ "unknown-object-field": func(c map[string]any, _ time.Time) { c["verified"] = true }, ++ } ++ for name, mutate := range cases { ++ t.Run(name, func(t *testing.T) { ++ admission, key, claims, now := identityFixture(t) ++ mutate(claims["assurance"].(map[string]any), now) ++ if _, err := VerifyApplicationIdentity(signedIdentity(t, key, claims, nil), admission, now); err == nil { ++ t.Fatal("malformed or stale issuer assurance accepted") ++ } ++ }) ++ } ++ for _, source := range []string{"", "assumed"} { ++ admission, key, claims, now := identityFixture(t) ++ claims["tenant_source"] = source ++ if _, err := VerifyApplicationIdentity(signedIdentity(t, key, claims, nil), admission, now); err == nil { ++ t.Fatal("missing or unknown tenant provenance accepted") ++ } ++ } ++} ++ ++func TestAccessEngineKeyCapeIdentityFactsAndFreshnessBounds(t *testing.T) { ++ admission, key, claims, now := identityFixture(t) ++ admission.MaxAuthenticationAge = "5s" ++ claims["assurance"].(map[string]any)["at"] = now.Add(-3 * time.Second).Unix() ++ identity, err := VerifyApplicationIdentity(signedIdentity(t, key, claims, nil), admission, now) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if !identity.NotAfter.Equal(now.Add(2*time.Second)) || !identity.AuthenticatedAt.Equal(now.Add(-3*time.Second)) || identity.TenantSource != "directory" { ++ t.Fatal("snapshot overstated authentication freshness or tenant provenance") ++ } ++ if _, ok := identity.AssuranceData["at"].(json.Number); !ok || identity.AssuranceData["mfa"] != true || identity.AssuranceData["source"] != "key-cape" { ++ t.Fatal("source assurance object lost its actual wire types") ++ } ++ admission.MaxIdentityAge = "2s" ++ identity, err = VerifyApplicationIdentity(signedIdentity(t, key, claims, nil), admission, now) ++ if err != nil || !identity.NotAfter.Equal(now.Add(time.Second)) { ++ t.Fatal("snapshot overstated token-age validity", err) ++ } ++} ++ ++func TestAccessEngineKeyCapeLowerAssuranceIsAnIdentityFact(t *testing.T) { ++ admission, key, claims, now := identityFixture(t) ++ claim := claims["assurance"].(map[string]any) ++ claim["level"] = "aal1" ++ claim["mfa"] = false ++ claim["methods"] = []string{"pwd"} ++ identity, err := VerifyApplicationIdentity(signedIdentity(t, key, claims, nil), admission, now) ++ if err != nil || identity.Assurance != "aal1" || identity.AssuranceData["mfa"] != false { ++ t.Fatal("identity parser substituted an application authorization policy", err) ++ } ++} +--- /dev/null ++++ b/services/auth/source/oauth2/access_engine_azp_test.go +@@ -0,0 +1,34 @@ ++package oauth2 ++ ++import "testing" ++ ++func TestAccessEngineAuthorizedPartyRefusesAnotherClient(t *testing.T) { ++ for name, value := range map[string]any{ ++ "other-client": "other-client", ++ "number": 17, ++ "array": []string{"forgejo"}, ++ "empty": "", ++ } { ++ t.Run(name, func(t *testing.T) { ++ admission, key, claims, now := identityFixture(t) ++ claims["azp"] = value ++ token := signedIdentity(t, key, claims, nil) ++ if _, err := VerifyApplicationIdentity(token, admission, now); err == nil { ++ t.Fatal("a valid signature and audience concealed an invalid authorized party") ++ } ++ }) ++ } ++} ++ ++func TestAccessEngineAuthorizedPartyAcceptsAdmittedClient(t *testing.T) { ++ for _, multiple := range []bool{false, true} { ++ admission, key, claims, now := identityFixture(t) ++ claims["azp"] = admission.Audience ++ if multiple { ++ claims["aud"] = []string{admission.Audience, "another-resource"} ++ } ++ if _, err := VerifyApplicationIdentity(signedIdentity(t, key, claims, nil), admission, now); err != nil { ++ t.Fatal("admitted authorized party refused", err) ++ } ++ } ++} +--- /dev/null ++++ b/services/auth/source/oauth2/access_engine_callback_test.go +@@ -0,0 +1,194 @@ ++package oauth2 ++ ++import ( ++ "crypto/ed25519" ++ "crypto/rand" ++ "encoding/base64" ++ "encoding/json" ++ "encoding/pem" ++ "net/http" ++ "net/http/httptest" ++ "os" ++ "path/filepath" ++ "reflect" ++ "strings" ++ "sync/atomic" ++ "testing" ++ "time" ++ ++ authmodel "forgejo.org/models/auth" ++ "github.com/golang-jwt/jwt/v5" ++ "github.com/markbates/goth" ++ "github.com/markbates/goth/gothic" ++ "github.com/netkingdom/access-engine/pkg/api" ++ "github.com/netkingdom/access-engine/pkg/decisionpep" ++ "github.com/netkingdom/access-engine/testsupport/signfixture" ++) ++ ++// This fixture substitutes only Goth's completed authentication result. The ++// actual Source.Callback, JOSE verifier, HTTPS PEP client and producer signature ++// implementation execute. Actual issuer login and native admission are separate. ++func callbackFixture(t *testing.T, group, mode string) (*Source, *goth.User, *atomic.Int64) { ++ return callbackFixtureWithIdentity(t, group, mode, nil, "") ++} ++ ++func callbackFixtureWithIdentity(t *testing.T, group, mode string, suppliedAdmission *AccessEngineAdmission, suppliedToken string) (*Source, *goth.User, *atomic.Int64) { ++ t.Helper() ++ admission, identityKey, claims, _ := identityFixture(t) ++ identityToken := signedIdentity(t, identityKey, claims, nil) ++ if suppliedAdmission != nil { ++ admission, identityToken = *suppliedAdmission, suppliedToken ++ } ++ verified, err := VerifyApplicationIdentity(identityToken, admission, time.Now().UTC()) ++ if err != nil { ++ t.Fatal("callback fixture identity invalid") ++ } ++ pub, key, err := ed25519.GenerateKey(rand.Reader) ++ if err != nil { ++ t.Fatal(err) ++ } ++ calls := new(atomic.Int64) ++ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ calls.Add(1) ++ if r.URL.Path != "/v1/check" || r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer synthetic-caller" || r.Header.Get("Access-Engine-JSON-Profile") != decisionpep.JSONProfile { ++ t.Error("incorrect authenticated PDP request") ++ w.WriteHeader(403) ++ return ++ } ++ var request api.CheckRequest ++ decoder := json.NewDecoder(r.Body) ++ decoder.UseNumber() ++ if err := decoder.Decode(&request); err != nil { ++ t.Error(err) ++ w.WriteHeader(400) ++ return ++ } ++ c := request.Context ++ if request.Subject.ID != "user:synthetic" || request.Subject.Tenant != "tenant:synthetic" || request.Subject.Type != "human" || request.Action != "application.access" || request.Resource.ID != "application:forgejo" || c["identity_issuer"] != admission.Issuer || c["identity_assurance"] != "aal2" || c["identity_tenant"] != "tenant:synthetic" || c["source_id"] != json.Number("17") || !reflect.DeepEqual(c["identity_assurance_claim"], verified.AssuranceData) || c["identity_authenticated_at"] != verified.AuthenticatedAt.UTC().Format(time.RFC3339Nano) || c["identity_tenant_source"] != verified.TenantSource { ++ t.Error("PDP request did not use authenticated identity and source") ++ w.WriteHeader(400) ++ return ++ } ++ now := time.Now().UTC() ++ envelope := api.DecisionEnvelope{ID: "synthetic-decision", RequestID: request.ID, Effect: api.DecisionEffectAllow, MatchedPolicyVersion: "v1", Subject: request.Subject, Resource: request.Resource, Binding: api.NewDecisionBindingFor(request, request), Provenance: api.DecisionProvenance{Evaluator: "flex-auth/local", Mode: "standalone/" + decisionpep.JSONProfile, PolicyPackage: "forgejo.application-access", PolicyVersion: "v1", PolicyPackageDigest: "sha256:" + strings.Repeat("1", 64), RegistrySnapshotDigest: "sha256:" + strings.Repeat("2", 64), Caller: &api.CallerProvenance{Mode: "enforce", Principal: "system:serviceaccount:synthetic:forgejo", Audience: "access-engine", NotAfter: now.Add(time.Minute).Format(time.RFC3339Nano)}}} ++ api.CompleteDecision(&envelope, request, api.DecisionCompletion{AllowTTL: "10s", Now: now}) ++ switch mode { ++ case "deny": ++ envelope.Effect = api.DecisionEffectDeny ++ case "wrong-binding": ++ envelope.Binding.Subject.ID = "other" ++ case "wrong-pin": ++ envelope.Provenance.PolicyPackageDigest = "sha256:" + strings.Repeat("3", 64) ++ case "expired": ++ envelope.Lifetime.ExpiresAt = now.Add(-time.Hour).Format(time.RFC3339Nano) ++ } ++ if mode != "unsigned" { ++ signingKey := key ++ if mode == "wrong-key" { ++ _, signingKey, err = ed25519.GenerateKey(rand.Reader) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ } ++ if err := signfixture.Sign(&envelope, signingKey, "synthetic-pdp"); err != nil { ++ t.Error(err) ++ return ++ } ++ } ++ w.Header().Set("Content-Type", "application/json") ++ if err := json.NewEncoder(w).Encode(envelope); err != nil { ++ t.Error(err) ++ } ++ })) ++ t.Cleanup(server.Close) ++ dir := t.TempDir() ++ ca := filepath.Join(dir, "ca.pem") ++ token := filepath.Join(dir, "caller") ++ config := filepath.Join(dir, "admission.json") ++ if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600); err != nil { ++ t.Fatal(err) ++ } ++ if err := os.WriteFile(token, []byte("synthetic-caller"), 0600); err != nil { ++ t.Fatal(err) ++ } ++ admission.SourceName = "synthetic-source" ++ admission.Decision = 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: "forgejo.application-access", PolicyVersion: "v1", PolicyDigest: "sha256:" + strings.Repeat("1", 64), RegistryDigest: "sha256:" + strings.Repeat("2", 64), CallerPrincipal: "system:serviceaccount:synthetic:forgejo", CallerAudience: "access-engine", MaxTTL: "30s", MaxClockSkew: "2s"} ++ raw, err := json.Marshal(admission) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if err = os.WriteFile(config, raw, 0600); err != nil { ++ t.Fatal(err) ++ } ++ t.Setenv("FORGEJO_ACCESS_ENGINE_ADMISSION_FILE", config) ++ source := &Source{Provider: "openidConnect", ClientID: admission.Audience, RequiredClaimName: "groups", RequiredClaimValues: []string{"forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"}} ++ source.authSource = &authmodel.Source{ID: 17, Name: admission.SourceName} ++ user := &goth.User{UserID: "user:synthetic", IDToken: identityToken, RawData: map[string]any{"sub": "user:synthetic", "groups": []string{group}}} ++ previous := gothic.CompleteUserAuth ++ gothic.CompleteUserAuth = func(http.ResponseWriter, *http.Request) (goth.User, error) { return *user, nil } ++ t.Cleanup(func() { gothic.CompleteUserAuth = previous }) ++ return source, user, calls ++} ++ ++func TestAccessEngineActualCallbackAllowsAuthenticatedDecision(t *testing.T) { ++ for _, group := range []string{"forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"} { ++ t.Run(group, func(t *testing.T) { ++ source, user, calls := callbackFixture(t, group, "allow") ++ // Mutable UserInfo cannot supply identity assurance, issuer or tenant. ++ user.RawData["acr"] = "aal1" ++ user.RawData["assurance"] = map[string]any{"level": "aal1", "source": "attacker"} ++ user.RawData["tenant_source"] = "attacker" ++ user.RawData["tenant"] = "tenant:attacker" ++ user.RawData["iss"] = "https://attacker.invalid" ++ got, err := source.Callback(httptest.NewRequest(http.MethodGet, "https://forgejo.invalid/callback", nil), httptest.NewRecorder(), "") ++ if err != nil || got.UserID != user.UserID || calls.Load() != 1 { ++ t.Fatalf("callback result: err=%v requests=%d", err, calls.Load()) ++ } ++ }) ++ } ++} ++ ++func TestAccessEngineActualCallbackRefusesUnverifiedPDP(t *testing.T) { ++ for _, mode := range []string{"deny", "unsigned", "wrong-key", "wrong-pin", "wrong-binding", "expired"} { ++ t.Run(mode, func(t *testing.T) { ++ source, _, calls := callbackFixture(t, "forge-admins", mode) ++ got, err := source.Callback(httptest.NewRequest(http.MethodGet, "https://forgejo.invalid/callback", nil), httptest.NewRecorder(), "") ++ if err == nil || got.UserID != "" || got.IDToken != "" || calls.Load() != 1 { ++ t.Fatalf("unverified decision escaped callback: requests=%d err=%v", calls.Load(), err) ++ } ++ }) ++ } ++} ++ ++func TestAccessEngineActualCallbackChecksIdentityBeforePDP(t *testing.T) { ++ cases := map[string]func(*Source, *goth.User){ ++ "missing-token": func(_ *Source, u *goth.User) { u.IDToken = "" }, ++ "mismatched-user": func(_ *Source, u *goth.User) { u.UserID = "other" }, ++ "mismatched-subject": func(_ *Source, u *goth.User) { u.RawData["sub"] = "other" }, ++ "missing-groups": func(_ *Source, u *goth.User) { delete(u.RawData, "groups") }, ++ "wrong-source": func(s *Source, _ *goth.User) { s.authSource.Name = "other" }, ++ "wrong-provider": func(s *Source, _ *goth.User) { s.Provider = "other" }, ++ "wrong-audience": func(s *Source, _ *goth.User) { s.ClientID = "other" }, ++ "missing-admission": func(_ *Source, _ *goth.User) { t.Setenv("FORGEJO_ACCESS_ENGINE_ADMISSION_FILE", "") }, ++ "expired-token": func(_ *Source, u *goth.User) { ++ _, key, claims, now := identityFixture(t) ++ claims["exp"] = now.Add(-time.Hour).Unix() ++ u.IDToken = signedIdentity(t, key, claims, nil) ++ }, ++ "untrusted-identity": func(_ *Source, u *goth.User) { ++ token := jwt.NewWithClaims(jwt.SigningMethodNone, jwt.MapClaims{"sub": "user:synthetic"}) ++ u.IDToken, _ = token.SignedString(jwt.UnsafeAllowNoneSignatureType) ++ }, ++ } ++ for name, mutate := range cases { ++ t.Run(name, func(t *testing.T) { ++ source, user, calls := callbackFixture(t, "forge-admins", "allow") ++ mutate(source, user) ++ got, err := source.Callback(httptest.NewRequest(http.MethodGet, "https://forgejo.invalid/callback", nil), httptest.NewRecorder(), "") ++ if err == nil || got.UserID != "" || calls.Load() != 0 { ++ t.Fatalf("unverified identity reached PDP: requests=%d err=%v", calls.Load(), err) ++ } ++ }) ++ } ++} +--- /dev/null ++++ b/services/auth/source/oauth2/access_engine_test.go +@@ -0,0 +1,100 @@ ++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: "assurance", TenantSourceClaim: "tenant_source", MaxAuthenticationAge: "5m", 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", "tenant_source": "directory", "assurance": map[string]any{"level": "aal2", "mfa": true, "source": "key-cape", "methods": []string{"pwd", "otp"}, "at": now.Add(-time.Second).Unix()}} ++ 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, "assurance") }, "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") ++ } ++ }) ++} +--- a/services/auth/source/oauth2/providers_openid.go ++++ b/services/auth/source/oauth2/providers_openid.go +@@ -4,6 +4,7 @@ + package oauth2 + + import ( ++ "errors" + "html/template" + + "forgejo.org/modules/log" +@@ -43,6 +44,22 @@ + if err != nil { + log.Warn("Failed to create OpenID Connect Provider with name '%s' with url '%s': %v", providerName, source.OpenIDConnectAutoDiscoveryURL, err) + } ++ if err != nil { ++ return nil, err ++ } ++ if source.RequiredClaimValues != nil { ++ if err := ValidateRequiredClaimValues(source.RequiredClaimName, source.RequiredClaimValue, source.RequiredClaimValues); err != nil { ++ return nil, err ++ } ++ if provider.OpenIDConfig == nil || provider.SkipUserInfoRequest { ++ return nil, errors.New("required-claim-values needs current UserInfo") ++ } ++ guarded, err := RequireCurrentUserInfoClaim(provider.Client(), provider.OpenIDConfig.UserInfoEndpoint, source.RequiredClaimName) ++ if err != nil { ++ return nil, err ++ } ++ provider.HTTPClient = guarded ++ } + return provider, err + } + +--- /dev/null ++++ b/services/auth/source/oauth2/required_claim_values.go +@@ -0,0 +1,202 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++ ++package oauth2 ++ ++import ( ++ "bytes" ++ "encoding/json" ++ "errors" ++ "io" ++ "net/http" ++ "net/url" ++ "strings" ++ "unicode" ++ "unicode/utf8" ++) ++ ++const maxClaimValues = 1024 ++const maxUserInfoBytes = 1 << 20 ++ ++// ValidateRequiredClaimValues validates only the opt-in list extension. A nil ++// list retains every legacy single-value behavior. An explicitly empty list ++// fails closed rather than turning a configured gate into claim-presence-only. ++func ValidateRequiredClaimValues(name, legacy string, values []string) error { ++ if values == nil { ++ return nil ++ } ++ if !validClaimLiteral(name) || legacy != "" || len(values) == 0 || len(values) > 64 { ++ return errors.New("invalid or conflicting required-claim-values configuration") ++ } ++ seen := map[string]bool{} ++ for _, value := range values { ++ if !validClaimLiteral(value) || seen[value] { ++ return errors.New("invalid required-claim-values literal") ++ } ++ seen[value] = true ++ } ++ return nil ++} ++ ++func validClaimLiteral(value string) bool { ++ return value != "" && len(value) <= 256 && utf8.ValidString(value) && ++ value == strings.TrimSpace(value) && !strings.ContainsAny(value, "\x00\r\n,") && ++ !strings.ContainsFunc(value, func(r rune) bool { return unicode.IsControl(r) || r == utf8.RuneError }) ++} ++ ++// strictClaimValues accepts only a well-formed claim array. No scalar parsing, ++// coercion, regex or prefix matching is introduced into the new gate. ++func strictClaimValues(raw any) ([]string, bool) { ++ var values []string ++ switch v := raw.(type) { ++ case []string: ++ values = v ++ case []any: ++ values = make([]string, len(v)) ++ for i, value := range v { ++ s, ok := value.(string) ++ if !ok { ++ return nil, false ++ } ++ values[i] = s ++ } ++ default: ++ return nil, false ++ } ++ if len(values) > maxClaimValues { ++ return nil, false ++ } ++ for _, value := range values { ++ if !validClaimLiteral(value) { ++ return nil, false ++ } ++ } ++ return values, true ++} ++ ++// MatchRequiredClaimValues evaluates the new consumer gate against current ++// authenticated provider data; it does not mutate or manufacture issuer claims. ++func MatchRequiredClaimValues(claims map[string]any, name, legacy string, required []string) bool { ++ if required == nil || ValidateRequiredClaimValues(name, legacy, required) != nil { ++ return false ++ } ++ raw, present := claims[name] ++ if !present { ++ return false ++ } ++ values, ok := strictClaimValues(raw) ++ if !ok { ++ return false ++ } ++ for _, value := range values { ++ for _, wanted := range required { ++ if value == wanted { ++ return true ++ } ++ } ++ } ++ return false ++} ++ ++// RequireCurrentUserInfoClaim preserves the existing HTTP client settings and ++// adds a strict response guard for this opt-in source only. A current UserInfo ++// array must overwrite any stale ID-token claim. Missing/invalid data and HTTP ++// failures cannot fall back to the ID-token map in Goth's merging code. ++func RequireCurrentUserInfoClaim(client *http.Client, endpoint, claim string) (*http.Client, error) { ++ u, err := url.Parse(endpoint) ++ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Fragment != "" || !validClaimLiteral(claim) { ++ return nil, errors.New("required-claim-values needs an HTTPS UserInfo endpoint") ++ } ++ if client == nil { ++ client = http.DefaultClient ++ } ++ result := *client ++ base := result.Transport ++ if base == nil { ++ base = http.DefaultTransport ++ } ++ result.Transport = ¤tClaimTransport{base: base, endpoint: endpoint, claim: claim} ++ // Redirects could evade endpoint matching or send a bearer to another origin. ++ // They are unsupported for the new guarded provider; legacy clients are intact. ++ result.CheckRedirect = func(*http.Request, []*http.Request) error { ++ return errors.New("guarded OAuth redirects are not supported") ++ } ++ return &result, nil ++} ++ ++type currentClaimTransport struct { ++ base http.RoundTripper ++ endpoint, claim string ++} ++ ++func (t *currentClaimTransport) RoundTrip(req *http.Request) (*http.Response, error) { ++ response, err := t.base.RoundTrip(req) ++ if req.URL.String() != t.endpoint { ++ return response, err ++ } ++ if err != nil { ++ if response != nil && response.Body != nil { ++ response.Body.Close() ++ } ++ return nil, errors.New("current UserInfo lookup failed") ++ } ++ if response == nil || response.Body == nil { ++ return nil, errors.New("current UserInfo response missing") ++ } ++ defer response.Body.Close() ++ if req.Method != http.MethodGet || response.StatusCode != http.StatusOK { ++ return nil, errors.New("current UserInfo refused") ++ } ++ body, err := io.ReadAll(io.LimitReader(response.Body, maxUserInfoBytes+1)) ++ if err != nil || len(body) > maxUserInfoBytes || !utf8.Valid(body) { ++ return nil, errors.New("current UserInfo response invalid") ++ } ++ // Reject duplicate top-level keys before Unmarshal can hide a conflicting ++ // groups or subject claim. json.RawMessage permits unrelated normal claims. ++ decoder := json.NewDecoder(bytes.NewReader(body)) ++ token, err := decoder.Token() ++ if err != nil || token != json.Delim('{') { ++ return nil, errors.New("current UserInfo object required") ++ } ++ claims := map[string]json.RawMessage{} ++ for decoder.More() { ++ keyToken, err := decoder.Token() ++ if err != nil { ++ return nil, errors.New("current UserInfo key invalid") ++ } ++ key, ok := keyToken.(string) ++ if !ok { ++ return nil, errors.New("current UserInfo key invalid") ++ } ++ if _, duplicate := claims[key]; duplicate { ++ return nil, errors.New("current UserInfo duplicate claim") ++ } ++ var value json.RawMessage ++ if decoder.Decode(&value) != nil { ++ return nil, errors.New("current UserInfo value invalid") ++ } ++ claims[key] = value ++ } ++ if token, err = decoder.Token(); err != nil || token != json.Delim('}') { ++ return nil, errors.New("current UserInfo object invalid") ++ } ++ var trailing any ++ if decoder.Decode(&trailing) != io.EOF { ++ return nil, errors.New("current UserInfo trailing data") ++ } ++ raw, present := claims[t.claim] ++ if !present { ++ return nil, errors.New("current UserInfo required claim missing") ++ } ++ var value any ++ if json.Unmarshal(raw, &value) != nil { ++ return nil, errors.New("current UserInfo required claim invalid") ++ } ++ if _, ok := strictClaimValues(value); !ok { ++ return nil, errors.New("current UserInfo required claim array invalid") ++ } ++ // Return the original public response bytes to Goth. Subject equality and ++ // audience/issuer checks remain in its existing authenticated provider path. ++ response.Body = io.NopCloser(bytes.NewReader(body)) ++ return response, nil ++} +--- /dev/null ++++ b/services/auth/source/oauth2/required_claim_values_test.go +@@ -0,0 +1,144 @@ ++// Copyright 2026 The Forgejo Authors. All rights reserved. ++// SPDX-License-Identifier: MIT ++package oauth2 ++ ++import ( ++ "errors" ++ "io" ++ "net/http" ++ "reflect" ++ "strings" ++ "testing" ++) ++ ++var caseValues = []string{"forge-admins", "forge-coulomb-owners", "forge-coulomb-readers"} ++ ++type roundTripFunc func(*http.Request) (*http.Response, error) ++ ++func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } ++ ++func mockUserInfo(body string, status int) *http.Client { ++ return &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { ++ return &http.Response{StatusCode: status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil ++ })} ++} ++ ++func TestRequiredClaimExactAnyOfAndNoMutation(t *testing.T) { ++ for _, group := range caseValues { ++ groups := []any{group, "unrelated"} ++ claims := map[string]any{"groups": groups, "other": "preserved"} ++ if !MatchRequiredClaimValues(claims, "groups", "", caseValues) { ++ t.Fatal("individual allowed group rejected") ++ } ++ if !reflect.DeepEqual(claims, map[string]any{"groups": groups, "other": "preserved"}) { ++ t.Fatal("claims mutated") ++ } ++ } ++ if !MatchRequiredClaimValues(map[string]any{"groups": append([]string(nil), caseValues...)}, "groups", "", caseValues) { ++ t.Fatal("multiple allowed groups rejected") ++ } ++ for _, raw := range []any{nil, true, 1, "forge-admins", "forge-admins,forge-coulomb-owners", []any{"forge-admins", 1}, []any{"forge-admins", nil}, []string{}, []any{}, []string{"forge-admins-lookalike"}, []string{" Forge-admins"}, []string{"forge-admins\n"}, []string{"Forge-admins"}, []string{"forge-admins,other"}, []string{"forge-admins", ""}} { ++ if MatchRequiredClaimValues(map[string]any{"groups": raw}, "groups", "", caseValues) { ++ t.Fatal("malformed/nonmatching claim accepted") ++ } ++ } ++ if MatchRequiredClaimValues(map[string]any{}, "groups", "", caseValues) { ++ t.Fatal("absent claim accepted") ++ } ++ if MatchRequiredClaimValues(map[string]any{"unrelated": []string{"forge-admins"}}, "groups", "", caseValues) { ++ t.Fatal("unrelated claim used") ++ } ++} ++ ++func TestRequiredClaimConfigurationRefusalsAndLegacyIsolation(t *testing.T) { ++ if ValidateRequiredClaimValues("", "old arbitrary literal", nil) != nil { ++ t.Fatal("legacy config changed") ++ } ++ for _, cfg := range []struct { ++ name, legacy string ++ values []string ++ }{ ++ {"groups", "", []string{}}, {"groups", "", []string{""}}, {"groups", "old", caseValues}, {"", "", caseValues}, ++ {"groups", "", []string{"a", "a"}}, {"groups", "", []string{"a,b"}}, {"groups", "", []string{" a"}}, ++ } { ++ if ValidateRequiredClaimValues(cfg.name, cfg.legacy, cfg.values) == nil { ++ t.Fatal("invalid config accepted") ++ } ++ } ++ if ValidateRequiredClaimValues("groups", "", caseValues) != nil { ++ t.Fatal("case config invalid") ++ } ++} ++ ++func TestCurrentUserInfoGuardRejectsMissingMalformedAndUnavailable(t *testing.T) { ++ for _, body := range []string{ ++ `{}`, `{"sub":"alice"}`, `{"groups":null}`, `{"groups":true}`, `{"groups":"forge-admins"}`, ++ `{"groups":["forge-admins",null]}`, `{"groups":["forge-admins",1]}`, ++ `{"groups":["forge-admins"],"groups":[]}`, `{"groups":[]} {}`, `[]`, `{"groups":[]`, ++ `{"groups":["forge-admins",""]}`, strings.Repeat(" ", maxUserInfoBytes+1), ++ } { ++ client, err := RequireCurrentUserInfoClaim(mockUserInfo(body, 200), "https://issuer.example/userinfo", "groups") ++ if err != nil { ++ t.Fatal(err) ++ } ++ response, err := client.Get("https://issuer.example/userinfo") ++ if err == nil { ++ response.Body.Close() ++ t.Fatal("invalid current claim did not fail closed") ++ } ++ } ++ client, _ := RequireCurrentUserInfoClaim(mockUserInfo(`{"groups":[]}`, 503), "https://issuer.example/userinfo", "groups") ++ if response, err := client.Get("https://issuer.example/userinfo"); err == nil { ++ response.Body.Close() ++ t.Fatal("non200 accepted") ++ } ++ broken := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, errors.New("private backend error") })} ++ client, _ = RequireCurrentUserInfoClaim(broken, "https://issuer.example/userinfo", "groups") ++ if _, err := client.Get("https://issuer.example/userinfo"); err == nil || strings.Contains(err.Error(), "private backend") { ++ t.Fatal("lookup failure not contained") ++ } ++} ++ ++func TestCurrentUserInfoEmptyArrayOverwritesAndGroupRemoval(t *testing.T) { ++ for _, body := range []string{`{"sub":"alice","groups":[]}`, `{"sub":"alice","groups":["forge-coulomb-readers"]}`} { ++ client, err := RequireCurrentUserInfoClaim(mockUserInfo(body, 200), "https://issuer.example/userinfo", "groups") ++ if err != nil { ++ t.Fatal(err) ++ } ++ response, err := client.Get("https://issuer.example/userinfo") ++ if err != nil { ++ t.Fatal(err) ++ } ++ b, _ := io.ReadAll(response.Body) ++ response.Body.Close() ++ if string(b) != body { ++ t.Fatal("response changed") ++ } ++ } ++} ++ ++func TestCurrentUserInfoGuardIsOptInAndRedirectsRefuse(t *testing.T) { ++ original := mockUserInfo(`{"unrelated":true}`, 200) ++ guarded, err := RequireCurrentUserInfoClaim(original, "https://issuer.example/userinfo", "groups") ++ if err != nil { ++ t.Fatal(err) ++ } ++ response, err := original.Get("https://issuer.example/userinfo") ++ if err != nil { ++ t.Fatal("original client mutated") ++ } ++ response.Body.Close() ++ response, err = guarded.Get("https://issuer.example/unrelated") ++ if err != nil { ++ t.Fatal("unrelated endpoint changed") ++ } ++ response.Body.Close() ++ if guarded.CheckRedirect == nil || guarded.CheckRedirect(nil, nil) == nil { ++ t.Fatal("redirect can bypass guard") ++ } ++ for _, endpoint := range []string{"", "http://issuer.example/userinfo", "https://user:pass@issuer.example/userinfo", "https://issuer.example/userinfo#fragment"} { ++ if _, err := RequireCurrentUserInfoClaim(original, endpoint, "groups"); err == nil { ++ t.Fatal("invalid endpoint accepted") ++ } ++ } ++} +--- a/services/auth/source/oauth2/source.go ++++ b/services/auth/source/oauth2/source.go +@@ -22,6 +22,7 @@ + Scopes []string + AttributeSSHPublicKey string + RequiredClaimName string ++ RequiredClaimValues []string `json:",omitempty"` + RequiredClaimValue string + GroupClaimName string + AdminGroup string +--- a/services/auth/source/oauth2/source_callout.go ++++ b/services/auth/source/oauth2/source_callout.go +@@ -64,5 +64,11 @@ + return user, err + } + ++ if source.RequiredClaimValues != nil { ++ if err := source.authorizeAccessEngine(request.Context(), user); err != nil { ++ return goth.User{}, err ++ } ++ } ++ + return user, nil + } +--- /dev/null ++++ b/third_party/access-engine-pep/LICENSE +@@ -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`. +--- /dev/null ++++ b/third_party/access-engine-pep/go.mod +@@ -0,0 +1,3 @@ ++module github.com/netkingdom/access-engine ++ ++go 1.24 +--- /dev/null ++++ b/third_party/access-engine-pep/internal/sign/sign.go +@@ -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 ++} +--- /dev/null ++++ b/third_party/access-engine-pep/pkg/api/canonical.go +@@ -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"` ++} +--- /dev/null ++++ b/third_party/access-engine-pep/pkg/api/caring.go +@@ -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"` ++} +--- /dev/null ++++ b/third_party/access-engine-pep/pkg/api/resource_manifest.go +@@ -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" +--- /dev/null ++++ b/third_party/access-engine-pep/pkg/decisionpep/client.go +@@ -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 ++} +--- /dev/null ++++ b/third_party/access-engine-pep/pkg/decisionpep/client_test.go +@@ -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") ++ } ++} +--- /dev/null ++++ b/third_party/access-engine-pep/producer-source.json +@@ -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" ++ } ++} +--- /dev/null ++++ b/third_party/access-engine-pep/testsupport/signfixture/sign.go +@@ -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) ++} diff --git a/build/forgejo/inputs.lock.json b/build/forgejo/inputs.lock.json index 743f819..645c5cb 100644 --- a/build/forgejo/inputs.lock.json +++ b/build/forgejo/inputs.lock.json @@ -3,13 +3,13 @@ "forgejo_version": "11.0.3", "source_archive_sha256": "1ddd8c926ca07d40436897971458ace7dcf1d3496a0813ab9e0d869edef2365c", "source_commit": "b81aa4d0807cc1e2d6a2fbafd0b75c46cc0ae237", - "patch_sha256": "f2788b3f2bf84dbc0f94e232b6c9614a864b8123c09f9e44703d50d5e1b53257", + "patch_sha256": "15cb7f13b1b1d1095cc344176ca337f705333a436a70ae803fcfd3d7f802ccf4", "go_archive_sha256": "3333f6ea53afa971e9078895eaa4ac7204a8c6b5c68c10e6bc9a33e8e391bdd8", "go_version": "1.24.3", "node_archive_sha256": "dafe2e8f82cb97de1bd10db9e2ec4c07bbf53389b0799b1e095a918951e78fd4", "node_version": "22.15.0", "source_date_epoch": 1752105237, - "release_version": "11.0.3+nk48.f2788b3f", + "release_version": "11.0.3+cust80.15cb7f13", "tags": "bindata timetzdata sqlite sqlite_unlock_notify", "runtime_base": "code.forgejo.org/forgejo/forgejo@sha256:41649dff5311664097d29b4d80620403f0b27e7c0eee0b8af79b132a37f3807b", "runtime_index_digest": "sha256:691657c7e64af7730a2e885e6d022cf16ae60724931c5392bd61838afadcaeba", @@ -17,7 +17,59 @@ "reviewed_outputs": [ { "path": "cmd/admin_auth_oauth.go", - "sha256": "1dd03f0bd23889a340a10fcc18d2e3a49270b79056aafd1b3baf01b18559b37f" + "sha256": "d718d817c46f6393488a9c5a894b7535640cd0ec1a1ae3f72f8411a2bbec3b38" + }, + { + "path": "cmd/admin_auth_oauth_secret_linux.go", + "sha256": "6741961f1df67c1afbf34c796e549425f0e04a0d0678c6eedb05f66d4754c64b" + }, + { + "path": "cmd/admin_auth_oauth_secret_linux_test.go", + "sha256": "b28c2369dfab9bf2ca48e707e01b4394a36c8be5490cfe5bb658017bb626c4b2" + }, + { + "path": "cmd/admin_auth_oauth_secret_other.go", + "sha256": "54056c989a4757e73db0252130e7c16bf16f5ec8eaaca2468f019ba2ef5c532d" + }, + { + "path": "go.mod", + "sha256": "130138c4c3ecc29fa0d7f1e2eef0589ddf3b06071f3cc0448aa7b2326847653a" + }, + { + "path": "models/auth/source_operation.go", + "sha256": "ef1b07ef6cf454015d00cde8588835f5118d829da91eb0303d37184859345a31" + }, + { + "path": "models/auth/source_operation_internal_test.go", + "sha256": "af0f424d3a1fd2b29793b64baa1fa07284fee7ea0b7721c503db4efac0d871cb" + }, + { + "path": "models/auth/source_operation_process_test.go", + "sha256": "40d33b11a01cb659f0bf6f8b545c4d79910e8c082a789060bcbc9cadeee965bd" + }, + { + "path": "models/auth/source_operation_test.go", + "sha256": "77d311bca42f48faf3fbdc15c53582e3d8a6d9108a72ed7bb6172e5b88951428" + }, + { + "path": "models/db/context.go", + "sha256": "d4c4acfcb8987071aecf5cd957b3821c8d2619a2696398d37c2970f2527686f7" + }, + { + "path": "models/db/engine.go", + "sha256": "43683804d0c5bc6ead1dba0344c69dd196825cf3d5eb502af8d932a7b8207b96" + }, + { + "path": "models/db/sensitive_sql.go", + "sha256": "06a298d0d6e628e6920384d4ddeef449e40c090841ebaa3f6d175725a45ae584" + }, + { + "path": "models/db/sensitive_sql_logging_test.go", + "sha256": "d924b35d30686473caf29601cf51cc363ba68158cb4ef0981c9e2fc7b03c04b7" + }, + { + "path": "models/db/sensitive_sql_test.go", + "sha256": "de6353c955047c3311747e4777b9f9b2195e9efb19160b971dd758dfc94cf31b" }, { "path": "routers/web/admin/auths.go", @@ -25,7 +77,31 @@ }, { "path": "routers/web/auth/oauth.go", - "sha256": "081bcb94023d6e27289196bbe518bebba0a8a6082ea1a32d2794c5562075907b" + "sha256": "58bff778e0dc17a521706289bf45c3e0d76a759a0874f76c379b3d1ddb419b17" + }, + { + "path": "services/auth/source/oauth2/access_engine.go", + "sha256": "d5f07f9491ac2212410e1fa8c0248d68ba3a723e7ca99e363627c5292d187aa8" + }, + { + "path": "services/auth/source/oauth2/access_engine_assurance.go", + "sha256": "42de751b1e9a243301d566260954813b770558ecb449639acaeab307fe788642" + }, + { + "path": "services/auth/source/oauth2/access_engine_assurance_test.go", + "sha256": "44e7459f6c1106a264093c19d61d01a8365f6ad22682906552d832ba39d61dd3" + }, + { + "path": "services/auth/source/oauth2/access_engine_azp_test.go", + "sha256": "5f94f43ade9a79b6b7ef529c80115a8c32acfece425dc8ed3f24e6ad839fc0ce" + }, + { + "path": "services/auth/source/oauth2/access_engine_callback_test.go", + "sha256": "5cea36b630c895a9473dc876b7128526ddef65d9395b2fddc56343e162452472" + }, + { + "path": "services/auth/source/oauth2/access_engine_test.go", + "sha256": "99edd6cfe3e834d73e0447a7915f52cc4ab7b82644669c5ae61963f850b447e8" }, { "path": "services/auth/source/oauth2/providers_openid.go", @@ -42,10 +118,54 @@ { "path": "services/auth/source/oauth2/source.go", "sha256": "44e99883c2ec479427b3f72c73353fe33936eed2e5c962b2fa40803576aa5642" + }, + { + "path": "services/auth/source/oauth2/source_callout.go", + "sha256": "6abba69df97afc62467f0328eaa5a6383cfb4900202a081dec4b84a21b37349c" + }, + { + "path": "third_party/access-engine-pep/LICENSE", + "sha256": "ff413f361a3b3bf44cf50f110fbcc4837064d57eefbcef89df2b43997c6262b6" + }, + { + "path": "third_party/access-engine-pep/go.mod", + "sha256": "fea700810e47c1ba5638b86a168f8531c083a6e1222ca80bd2a8947b2ea6f2c3" + }, + { + "path": "third_party/access-engine-pep/internal/sign/sign.go", + "sha256": "0df9515922e90775ebbfac798361dcafb20da8a4213796b44e246b8a92046cde" + }, + { + "path": "third_party/access-engine-pep/pkg/api/canonical.go", + "sha256": "a122a2e8cd524333b13c5939c7a3685e41efbe47497a64e0c7297c92b7f10d19" + }, + { + "path": "third_party/access-engine-pep/pkg/api/caring.go", + "sha256": "1907156f0f889e7b9e9c14970cf7a86a20d00478a496efaf92c7231f27fec5e3" + }, + { + "path": "third_party/access-engine-pep/pkg/api/resource_manifest.go", + "sha256": "f0fa4080287d389ed48c2b1d6af96cc62e57ef72c902333f677f964420be133f" + }, + { + "path": "third_party/access-engine-pep/pkg/decisionpep/client.go", + "sha256": "0d57f6ddaca5c3f81ce426c0e8b14ba14ea5962096d3be5909aa456eef19eeba" + }, + { + "path": "third_party/access-engine-pep/pkg/decisionpep/client_test.go", + "sha256": "1a6be3485f580f95a1f1406fb76e525f2c4bf02fe04a424cfe0095bb728e3f62" + }, + { + "path": "third_party/access-engine-pep/producer-source.json", + "sha256": "c1d83e3d79f9860ffaa61ec19a6b3415e914d3058b11b07cdd05a7d1182cdceb" + }, + { + "path": "third_party/access-engine-pep/testsupport/signfixture/sign.go", + "sha256": "fe4aa86f444dc20145aefbaca35b24f046264b2c5c8b4e3b057a4496b77a4d29" } ], "lockfiles": { - "go.mod": "652162a4a95c6d1c349d2a8c0b514def5abd837f001137b77b7b3f4a0f162d00", + "go.mod": "130138c4c3ecc29fa0d7f1e2eef0589ddf3b06071f3cc0448aa7b2326847653a", "go.sum": "19c305c7e68de9d3f1bc0dda2de09c5d38597f1ee7fa411c7b36b92467ae1eaf", "package.json": "ab5c54ec7077501b50acf3ab5f1fff4f63a51abe99e720b8ecdc6cc6c78f39fc", "package-lock.json": "fdd5c2f891311be7c01b1907b418c243ca1f0f951fd4b4ee5b5e931c43493657" @@ -59,5 +179,8 @@ "/usr/lib/x86_64-linux-gnu/libc.a": "a40c7eae7581f977b65eddb81cbc799213a695749e039d966db55bdee4ac9621", "/usr/lib/x86_64-linux-gnu/libm.a": "420cd3c406f6f8c12deb3d1291146e9c091ee015a7c39eaf2237f01e80d6f0ae" }, - "runtime_base_config_sha256": "bc5a3df111729582faadebd01d126ba769e2b65d0c62f306f6bc79f4e562452b" + "runtime_base_config_sha256": "bc5a3df111729582faadebd01d126ba769e2b65d0c62f306f6bc79f4e562452b", + "patch_file": "forgejo-security-extension.patch", + "candidate_review_status": "coordinator tested; independent owner review pending", + "producer_source_commit": "ca0cb75729a63c9288b7333382d0fa3eb1e8c9a3" } diff --git a/tools/forgejo-release-build.py b/tools/forgejo-release-build.py index 08524d2..491f710 100644 --- a/tools/forgejo-release-build.py +++ b/tools/forgejo-release-build.py @@ -73,7 +73,7 @@ def prepare(a,work): check(getattr(a,n),LOCK[key]) if not a.module_cache:raise ValueError('explicit public module cache required') cache=Path(a.module_cache).resolve();assert cache.is_dir() - check(INPUTS/'required-claim-values.patch',LOCK['patch_sha256']) + check(INPUTS/LOCK['patch_file'],LOCK['patch_sha256']) for n,h in LOCK['host_tools'].items():check(n,h) work.mkdir(parents=True);(work/'home').mkdir() with tarfile.open(a.source_archive) as t: @@ -85,8 +85,8 @@ def prepare(a,work): for n in ['empty.npmrc','empty-global.npmrc']:(work/n).write_text('') if a.go_cache_seed:shutil.copytree(Path(a.go_cache_seed).resolve(),work/'gocache') if a.npm_cache_seed:shutil.copytree(Path(a.npm_cache_seed).resolve(),work/'npm-cache') - subprocess.run(['/usr/bin/git','apply','--check',str(INPUTS/'required-claim-values.patch')],cwd=work/'source',check=True,env={'PATH':'/usr/bin:/bin','HOME':str(work/'home'),'GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'}) - subprocess.run(['/usr/bin/git','apply',str(INPUTS/'required-claim-values.patch')],cwd=work/'source',check=True,env={'PATH':'/usr/bin:/bin','HOME':str(work/'home'),'GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'}) + subprocess.run(['/usr/bin/git','apply','--check',str(INPUTS/LOCK['patch_file'])],cwd=work/'source',check=True,env={'PATH':'/usr/bin:/bin','HOME':str(work/'home'),'GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'}) + subprocess.run(['/usr/bin/git','apply',str(INPUTS/LOCK['patch_file'])],cwd=work/'source',check=True,env={'PATH':'/usr/bin:/bin','HOME':str(work/'home'),'GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'}) save(work/'prepared.json',{'module_cache':str(cache),'lock_sha256':digest(INPUTS/'inputs.lock.json'),'public_archives_verified':True}) checked_inputs(work) packages=json.loads((work/'source/package-lock.json').read_text())['packages'] @@ -136,6 +136,7 @@ def verify(work): run(work,'binary-version',bare+['--version'],outer) run(work,'new-cli-help',bare+['admin','auth','add-oauth','--help'],outer) assert '--required-claim-values' in (work/'new-cli-help.log').read_text() + assert '--secret-file' in (work/'new-cli-help.log').read_text() run(work,'embedded-extract',bare+['embedded','extract','--include-vendored','--destination','/results','**'],outer) records={} for folder in ['public','options','templates']: diff --git a/workplans/RAPPS-WP-0016-forgejo-netkingdom-login.md b/workplans/RAPPS-WP-0016-forgejo-netkingdom-login.md index 6abc696..e733dd0 100644 --- a/workplans/RAPPS-WP-0016-forgejo-netkingdom-login.md +++ b/workplans/RAPPS-WP-0016-forgejo-netkingdom-login.md @@ -246,7 +246,7 @@ its historical text is retained and corrected here. ```task id: RAPPS-WP-0016-T09 -status: todo +status: progress priority: high state_hub_task_id: "d3804638-c73d-5b9f-a456-4262f62f9e6b" ``` @@ -261,3 +261,23 @@ issuer allowed/denied claim cannot manufacture authorization. Source integration needs real provider/callback/session wiring and meaningful producer-consumer positive/adverse tests before re-freezing the case and package. Existing break- glass/local account and linking behavior remain within the declared owner scope. + +2026-10-18 source continuation for T07/T08/T09: the digest-bound build +candidate now composes all 37 paths, including private secret-file input, actual +source-state transactions/private SQL hooks, the producer-owned Access Engine +Check client from ca0cb757 and guarded OIDC callback enforcement. The parser uses +the actual KeyCape typed assurance/authentication-time/provenance contract; its +actual issuer fixture/callback suite passes 71 test/subtest results, and selected +composed packages pass 93 with no skips. The previous incompatible-string-claim +rejection is retained. All patch postimages independently replay from the pinned +official archive. Complete release build/verification is tracked in Custodian +forgejo-keycape-claims-r1; earlier release outputs do not prove this revision. + +This is coordinator source integration of a tested build candidate; independent +owner review and formal operational admission remain open. T07's chart/private +mount admission, T08's fresh authenticated operation/inverse and release-wide +writer exclusion, T09's ongoing HTTP/API/Git/SSH paths, private evidence/retention, +PostgreSQL/native proof and actual issuer/factor/custody acceptance remain open. +No trust, deployed image, Helm values, source DB, user/link state or local sign-in +is changed by this build-source update. The preserved legacy patch is historical; +the input lock now explicitly selects forgejo-security-extension.patch.