Skip to content

Commit fff04d6

Browse files
authored
[Add] enforce Decider, reader helpers (#31)
1 parent f2a0183 commit fff04d6

7 files changed

Lines changed: 511 additions & 26 deletions

File tree

‎cmd/borg/enforce_test.go‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func (h *harness) enforcer(t *testing.T, org string) *enforce.Enforcer {
3535
}
3636
return &enforce.Enforcer{
3737
Reader: &reader.Client{Hosts: []string{h.aS.URL, h.bS.URL}, Headers: h.chain, HTTP: http.DefaultClient, Timeout: 5 * time.Second},
38-
Spends: spendSource{c},
38+
Spends: spendSource(c),
3939
Wallet: w.Signer(),
4040
Hall: h.hall,
4141
Org: raw,
@@ -124,3 +124,40 @@ func TestEnforceDeniesWithoutASpendSource(t *testing.T) {
124124
t.Fatalf("allow=%v reason=%q err=%v", v.Allow, v.Reason, err)
125125
}
126126
}
127+
128+
// A Decider over the same hosts decides as the Enforcer does, with no
129+
// wallet and no receipt: an allow, a deny reused for DenyFor, a stranger,
130+
// and a role retired on the chain seen once the allow is AllowFor old.
131+
func TestDeciderDecides(t *testing.T) {
132+
t.Parallel()
133+
h := newHarness(t)
134+
o := h.orgWithGroup()
135+
h.must("org", "role", "define", "releaser", "-permission", "bsecret/release/payroll")
136+
h.must("org", "bind", "releaser", "-to", o.group)
137+
e := h.enforcer(t, o.key)
138+
clock := time.Now()
139+
e.Reader.Floor = &reader.MemFloor{}
140+
d := &enforce.Decider{Reader: e.Reader, Spends: e.Spends, AllowFor: 30 * time.Second, DenyFor: 10 * time.Second,
141+
StaleFor: time.Minute, Now: func() time.Time { return clock }}
142+
org, _ := hex.DecodeString(o.key)
143+
alice, _ := hex.DecodeString(o.alice)
144+
stranger, _ := hex.DecodeString(h.identity("stranger", false))
145+
ctx := context.Background()
146+
if ok, err := d.Allows(ctx, h.hall, org, alice, "bsecret/release/payroll"); !ok || err != nil {
147+
t.Fatalf("alice: %v %v", ok, err)
148+
}
149+
if ok, err := d.Allows(ctx, h.hall, org, alice, "bstore/put/photos/a.jpg"); ok || err != nil {
150+
t.Fatalf("alice, a permission the role does not carry: %v %v", ok, err)
151+
}
152+
if ok, err := d.Allows(ctx, h.hall, org, stranger, "bsecret/release/payroll"); ok || err != nil {
153+
t.Fatalf("a stranger: %v %v", ok, err)
154+
}
155+
h.must("org", "role", "retire", "releaser")
156+
if ok, _ := d.Allows(ctx, h.hall, org, alice, "bsecret/release/payroll"); !ok {
157+
t.Fatal("within AllowFor the earlier allow is reused")
158+
}
159+
clock = clock.Add(31 * time.Second)
160+
if ok, err := d.Allows(ctx, h.hall, org, alice, "bsecret/release/payroll"); ok || err != nil {
161+
t.Fatalf("after the retire, AllowFor on: %v %v", ok, err)
162+
}
163+
}

‎cmd/borg/home.go‎

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -164,18 +164,9 @@ func (g *global) chainView() (*nodeapi.Sources, error) {
164164

165165
// spendSource is a chain view's answer to which outputs are spent, with
166166
// what the source named left out of an error's text and a spender in lower
167-
// case: what a source names is printed, compared and asked for again, and
168-
// a source is somebody else's server.
169-
type spendSource struct{ nodeapi.SpendSource }
170-
171-
// Spender is the source's answer.
172-
func (s spendSource) Spender(ctx context.Context, txid string, vout uint32) (string, error) {
173-
by, err := s.SpendSource.Spender(ctx, txid, vout)
174-
if err != nil {
175-
return "", reader.QuietSpend(err)
176-
}
177-
return strings.ToLower(by), nil
178-
}
167+
// case (reader.QuietSpends): what a source names is printed, compared and
168+
// asked for again, and a source is somebody else's server.
169+
func spendSource(s nodeapi.SpendSource) reader.Spends { return reader.QuietSpends(s) }
179170

180171
// spends is the configured spend source, or nil: the chain view's answer
181172
// to which outputs are spent.
@@ -184,17 +175,16 @@ func (g *global) spends() reader.Spends {
184175
if err != nil {
185176
return nil
186177
}
187-
return spendSource{c}
178+
return spendSource(c)
188179
}
189180

190181
// proofSource is a chain view as a reader's source of a mined
191182
// transaction's current proof.
192-
type proofSource struct{ nodeapi.ProofSource }
193-
194-
// MerkleProof is the source's proof.
195-
func (p proofSource) MerkleProof(ctx context.Context, txid string) (*transaction.MerklePath, error) {
196-
mp, _, err := p.Proof(ctx, txid)
197-
return mp, err
183+
func proofSource(p nodeapi.ProofSource) reader.ChainSource {
184+
return reader.ProofFunc(func(ctx context.Context, txid string) (*transaction.MerklePath, error) {
185+
mp, _, err := p.Proof(ctx, txid)
186+
return mp, err
187+
})
198188
}
199189

200190
// settler is the configured settlement leg (config key settle), with an
@@ -205,7 +195,7 @@ func (g *global) settler() (publish.Settler, *publish.Arcade, error) {
205195
}
206196
opt := publish.SettleOptions{Key: g.cfg.ArcadeKey, RPCUser: g.cfg.RPCUser, RPCPass: g.cfg.RPCPass, RPCID: "borg", Note: g.say}
207197
if c, err := g.chainView(); err == nil {
208-
opt.Spends = spendSource{c}
198+
opt.Spends = spendSource(c)
209199
}
210200
s, a, err := publish.ParseSettler(g.cfg.Settle, opt)
211201
if err != nil {
@@ -268,7 +258,7 @@ func (g *global) reader() (*reader.Client, error) {
268258
if c, err := g.chainView(); err == nil {
269259
// A proof a host stored that a reorganization left stale is
270260
// replaced by the chain view's current one (spec section 11.5).
271-
rd.Source = proofSource{c}
261+
rd.Source = proofSource(c)
272262
}
273263
return rd, nil
274264
}

‎docs/packages.md‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ of a copy of it, and a third decides on a requester's behalf. A fourth,
1111
| --- | --- |
1212
| `github.com/lightwebinc/borg/borgrec` | The byte-level contract ([spec.md](spec.md)): records, tokens, wraps, the folds, the registry values and the bounds. No network. |
1313
| `github.com/lightwebinc/borg/reader` | A client that asks overlay hosts the `ls_borg` questions and verifies every answer against the caller's own headers. |
14-
| `github.com/lightwebinc/borg/enforce` | The decision procedure of [spec.md](spec.md) section 13 behind one call, for a service deciding on a requester's behalf: fail-closed, with the signed receipt returned. |
14+
| `github.com/lightwebinc/borg/enforce` | The decision procedure of [spec.md](spec.md) section 13 behind one call: `Enforcer` for a service deciding on a requester's behalf, fail-closed, with the signed receipt returned; `Decider` for a service that decides for itself, with no wallet and no receipt, for any organization. |
1515
| `github.com/lightwebinc/borg/module` | The host module in Go, on bcommon's engine-neutral module contract: `tm_borg_` managers, `ls_borg` (also an ordered replayer), the terms route. A host calls `New` with its environment and runs `Mounted.Start`. |
1616

1717
## Supported surface
@@ -61,6 +61,11 @@ any tag.
6161
`Client.Source` (a `ChainSource`; bcommon's `nodeapi.Asset` is one).
6262
- `ChainView` (with `Beyond`: the verified tokens above the chain read),
6363
`GroupView`, `NewGroupView`.
64+
- `MemFloor`: a `Floor` kept in memory for as long as the process runs.
65+
- `QuietSpends`: a node's or an index's spend answer as a `Spends`, its
66+
errors through `QuietSpend` and the spender in lower case.
67+
`ProofFunc`: a function answering a mined transaction's proof as a
68+
`ChainSource`.
6469
- The policy set: `Client.PolicySet` (every host, all pages, each answer
6570
held to the root the latest token commits to), `Client.RoleOf`,
6671
`Client.BoundTo`, `OrgView.PolicyPathHolds`.
@@ -158,8 +163,32 @@ default), and at most 16 tokens are taken from one answer to a seq.
158163
most that stale, which is the staleness the service states.
159164
- The cache holds at most `MaxCached` allows and is cleared past that.
160165

161-
A service keeps an interface of its own in front of `Enforcer`, so that
162-
this package, and with it borg, is a dependency of one file.
166+
- `Decider`, made once and kept, for a service that decides for itself
167+
and keeps no receipt (a DNS renderer admitting writers by a permission,
168+
say): a `reader.Client` (give it a `Floor`), a `reader.Spends`, and
169+
`AllowFor`, `DenyFor`, `StaleFor`. `Decider.Allows(ctx, hall, org,
170+
subject, permission)` answers for any organization named.
171+
- An allow is reused for `AllowFor` (zero is `DefaultFreshness`) and a deny
172+
for `DenyFor` (zero is `DefaultDenyFor`, held to `AllowFor`), each only
173+
at the seq it was read at. The organization's latest token is read again
174+
at `AllowFor`, and at `DenyFor` while the subject asked about is denied,
175+
so a subject just granted waits `DenyFor` once the hosts hold the token.
176+
- It fails closed. A read it cannot complete is an error and a deny. A
177+
failed read of an organization is reused for `DenyFor`, unless the
178+
caller's own context ended it. A policy set that cannot be read whole
179+
(`reader.Decision.Reason` `incomplete`) is a failed read, not a deny, and
180+
so is a subject's grants answered by no host. An allow read before a
181+
failure stands for `StaleFor` from that read, only while no later token
182+
of the organization is verified, and is answered true with an error that
183+
wraps `ErrStale`; zero keeps none. A view never goes back to an earlier
184+
seq. A
185+
grant the spend source cannot show unspent is not current: a deny at
186+
once, as for a revoked one.
187+
- `Decider.Forget` drops everything reused.
188+
189+
A service keeps an interface of its own in front of `Enforcer` or
190+
`Decider`, so that this package, and with it borg, is a dependency of one
191+
file.
163192

164193
**`module`**
165194

‎enforce/decider.go‎

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
package enforce
2+
3+
import (
4+
"context"
5+
"encoding/hex"
6+
"errors"
7+
"fmt"
8+
"sync"
9+
"time"
10+
11+
"github.com/lightwebinc/borg/borgrec"
12+
"github.com/lightwebinc/borg/reader"
13+
)
14+
15+
// Decider is the decision procedure of spec section 13 for a service that
16+
// decides for itself, keeps no receipt and answers for any organization a
17+
// caller names: a renderer that admits writers by a permission, say. It is
18+
// Enforcer without the wallet and the receipt, and with what a service
19+
// that asks often and from many places needs: denies reused too, a failed
20+
// read remembered, and an allow kept through an outage for a bound the
21+
// service states. Make one and keep it; it is safe for concurrent use and
22+
// holds no lock over a read.
23+
//
24+
// It fails closed. A read it cannot complete is an error, and the answer is
25+
// a deny, except an allow read before the failure and within StaleFor,
26+
// which is answered true with an error that wraps ErrStale.
27+
type Decider struct {
28+
// Reader asks the hosts and verifies what they answer against the
29+
// service's own headers. Give it a Floor (reader.MemFloor at least), so
30+
// a host set that answers an older organization token than one already
31+
// verified is refused; without one a Decider still never goes back to
32+
// an earlier seq itself, but a restart, or a second Decider, can.
33+
Reader *reader.Client
34+
// Spends says whether an outpoint is spent. Without one nothing is
35+
// current and every call denies.
36+
Spends reader.Spends
37+
// AllowFor is how long an allow is reused, and how often the
38+
// organization's latest token is read again while every subject asked
39+
// about is allowed; zero is DefaultFreshness. A revoked grant is
40+
// answered at most this long past the hosts holding the token that
41+
// revoked it.
42+
AllowFor time.Duration
43+
// DenyFor is how long a deny, or a failed read of an organization, is
44+
// reused, and how often the latest token is read again while a subject
45+
// is denied: so a subject just granted waits this long once the hosts
46+
// hold the token. Zero is DefaultDenyFor; it is held to AllowFor.
47+
DenyFor time.Duration
48+
// StaleFor is how long an allow stands through failed reads, from the
49+
// read that allowed it, and only while no later token is verified.
50+
// Zero keeps none: a failed read denies.
51+
StaleFor time.Duration
52+
// Now is the clock; nil is time.Now.
53+
Now func() time.Time
54+
55+
mu sync.Mutex
56+
views map[string]deciderView
57+
answers map[string]deciderAnswer
58+
failed map[string]deciderFailure
59+
}
60+
61+
// DefaultDenyFor is how long a Decider reuses a deny when it is told no
62+
// bound of its own.
63+
const DefaultDenyFor = 10 * time.Second
64+
65+
// ErrStale marks an allow kept through a failed read: the organization
66+
// could not be read, and the subject was allowed when it last was, within
67+
// StaleFor.
68+
var ErrStale = errors.New("enforce: the organization could not be read; its last allow stands")
69+
70+
type deciderView struct {
71+
view *reader.OrgView
72+
at time.Time
73+
}
74+
75+
type deciderAnswer struct {
76+
allow bool
77+
seq uint64
78+
at time.Time
79+
}
80+
81+
type deciderFailure struct {
82+
err error
83+
at time.Time
84+
}
85+
86+
func (d *Decider) now() time.Time {
87+
if d.Now != nil {
88+
return d.Now()
89+
}
90+
return time.Now()
91+
}
92+
93+
func (d *Decider) allowFor() time.Duration {
94+
if d.AllowFor > 0 {
95+
return d.AllowFor
96+
}
97+
return DefaultFreshness
98+
}
99+
100+
func (d *Decider) denyFor() time.Duration {
101+
if d.DenyFor > 0 {
102+
return min(d.DenyFor, d.allowFor())
103+
}
104+
return min(DefaultDenyFor, d.allowFor())
105+
}
106+
107+
// Allows decides whether subject holds permission in the organization org
108+
// of hall now. The permission is asked in full, with no wildcard.
109+
func (d *Decider) Allows(ctx context.Context, hall string, org, subject []byte, permission string) (bool, error) {
110+
if d.Reader == nil || d.Spends == nil {
111+
return false, errors.New("enforce: a reader and a spend source are required")
112+
}
113+
if _, err := borgrec.Asked(permission); err != nil {
114+
return false, fmt.Errorf("enforce: %q is not a permission a service asks: %w", permission, err)
115+
}
116+
now := d.now()
117+
vk := hall + "|" + hex.EncodeToString(org)
118+
ak := vk + "|" + hex.EncodeToString(subject) + "|" + permission
119+
d.mu.Lock()
120+
v, f := d.views[vk], d.failed[vk]
121+
a, seen := d.answers[ak]
122+
d.mu.Unlock()
123+
// fail is a read that failed. An allow read within StaleFor stands,
124+
// but only at the seq it was read at: once a later token is verified,
125+
// an allow of an earlier one is never answered, so a host set that
126+
// withholds a revoking policy set cannot keep it.
127+
fail := func(err error) (bool, error) {
128+
if d.StaleFor > 0 && seen && a.allow && now.Sub(a.at) <= d.StaleFor && (v.view == nil || a.seq == v.view.Token.Seq) {
129+
return true, fmt.Errorf("%w: %v", ErrStale, err)
130+
}
131+
return false, err
132+
}
133+
stale := d.allowFor()
134+
if !seen || !a.allow {
135+
stale = d.denyFor()
136+
}
137+
if v.view == nil || now.Sub(v.at) >= stale {
138+
if f.err != nil && now.Sub(f.at) < d.denyFor() {
139+
return fail(f.err)
140+
}
141+
ov, err := d.Reader.Org(ctx, hall, org)
142+
if err != nil {
143+
err = fmt.Errorf("enforce: the organization's chain: %w", err)
144+
// A read cut short by the caller's own deadline says nothing of
145+
// the hosts, so it is not kept for other callers.
146+
if ctx.Err() == nil {
147+
d.mu.Lock()
148+
if len(d.failed) >= MaxCached {
149+
d.failed = nil
150+
}
151+
d.failed = setIn(d.failed, vk, deciderFailure{err: err, at: now})
152+
d.mu.Unlock()
153+
}
154+
return fail(err)
155+
}
156+
d.mu.Lock()
157+
// A read that lands after a later one keeps the later view: a
158+
// view never goes back to an earlier seq.
159+
if cur, ok := d.views[vk]; ok && cur.view.Token.Seq > ov.Token.Seq {
160+
v = cur
161+
} else {
162+
v = deciderView{view: ov, at: now}
163+
if len(d.views) >= MaxCached {
164+
d.views = nil
165+
}
166+
d.views = setIn(d.views, vk, v)
167+
}
168+
delete(d.failed, vk)
169+
d.mu.Unlock()
170+
}
171+
if seen && a.seq == v.view.Token.Seq && (a.allow && now.Sub(a.at) < d.allowFor() || !a.allow && now.Sub(a.at) < d.denyFor()) {
172+
return a.allow, nil
173+
}
174+
dec, err := d.Reader.Allows(ctx, v.view, subject, permission, d.Spends, now)
175+
if err != nil {
176+
return fail(err)
177+
}
178+
if dec.Reason == "incomplete" {
179+
// The policy set the token commits to could not be read whole: a
180+
// failed read, not a deny, and not kept as an answer.
181+
return fail(errors.New("enforce: the organization's policy set could not be read whole"))
182+
}
183+
if !dec.Allow && (ctx.Err() != nil || len(dec.HostErr) >= len(d.Reader.Hosts) && len(dec.Grants) == 0) {
184+
// No host answered the subject's grants (or the caller's context
185+
// ended the read): the reader folds that into "not-member" with
186+
// no error, and it is a failed read, not a deny, and not kept.
187+
return fail(fmt.Errorf("enforce: no host answered the subject's grants (%d host errors)", len(dec.HostErr)))
188+
}
189+
d.mu.Lock()
190+
if len(d.answers) >= MaxCached {
191+
d.answers = nil
192+
}
193+
d.answers = setIn(d.answers, ak, deciderAnswer{allow: dec.Allow, seq: dec.Seq, at: now})
194+
d.mu.Unlock()
195+
return dec.Allow, nil
196+
}
197+
198+
// Forget drops every reused answer, view and failure.
199+
func (d *Decider) Forget() {
200+
d.mu.Lock()
201+
defer d.mu.Unlock()
202+
d.views, d.answers, d.failed = nil, nil, nil
203+
}
204+
205+
func setIn[V any](m map[string]V, k string, v V) map[string]V {
206+
if m == nil {
207+
m = map[string]V{}
208+
}
209+
m[k] = v
210+
return m
211+
}

0 commit comments

Comments
 (0)