1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package trust
import (
"context"
"errors"
"slices"
"strings"
"time"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/market"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/atproto"
)
const (
KindClaim = "claim"
KindAssociation = "association"
KindBskyPost = "bskyPost"
KindDelvePost = "delvePost"
DefaultPostTemplate = "associate {did}"
)
var DefaultKinds = []string{KindClaim, KindAssociation}
type Association struct {
Kinds []string
PostTemplate string
MaxDepth int
RequireContract bool
}
type associationKey struct {
claim bool
association bool
bskyPost bool
delvePost bool
template string
requireContract bool
}
func (a Association) key() associationKey {
kinds := a.Kinds
if len(kinds) == 0 {
kinds = DefaultKinds
}
template := a.PostTemplate
if strings.TrimSpace(template) == "" {
template = DefaultPostTemplate
}
return associationKey{
claim: slices.Contains(kinds, KindClaim),
association: slices.Contains(kinds, KindAssociation),
bskyPost: slices.Contains(kinds, KindBskyPost),
delvePost: slices.Contains(kinds, KindDelvePost),
template: template,
requireContract: a.RequireContract,
}
}
func (k associationKey) allows(kind string) bool {
switch kind {
case KindClaim:
return k.claim
case KindAssociation:
return k.association
case KindBskyPost:
return k.bskyPost
case KindDelvePost:
return k.delvePost
}
return false
}
func KindOfCollection(collection string) string {
switch collection {
case BadgeBlueKeysNSID:
return KindClaim
case AssociationNSID:
return KindAssociation
case BskyPostNSID:
return KindBskyPost
case DelvePostNSID:
return KindDelvePost
}
return ""
}
func collectionOfKind(kind string) string {
switch kind {
case KindClaim:
return BadgeBlueKeysNSID
case KindAssociation:
return AssociationNSID
case KindBskyPost:
return BskyPostNSID
case KindDelvePost:
return DelvePostNSID
}
return ""
}
func Matches(kind string, value map[string]any, authority, subject, service, template string) bool {
if value == nil || authority == "" || subject == "" || authority == subject {
return false
}
if recordType, _ := value["$type"].(string); recordType != collectionOfKind(kind) {
return false
}
switch kind {
case KindClaim:
held, ok := claimOf(value)
return ok && held.operator == authority && held.subject == subject && associationService(held.service, service)
case KindAssociation:
recordSubject, _ := value["subject"].(string)
recordService, _ := value["service"].(string)
return recordSubject == subject && associationService(recordService, service)
case KindBskyPost, KindDelvePost:
return postMatches(value, subject, template)
}
return false
}
func postMatches(value map[string]any, subject, template string) bool {
if strings.TrimSpace(template) == "" {
template = DefaultPostTemplate
}
text, _ := value["text"].(string)
if strings.TrimSpace(text) != strings.TrimSpace(strings.ReplaceAll(template, "{did}", subject)) {
return false
}
mentions := 0
matched := false
facets, _ := value["facets"].([]any)
for _, facet := range facets {
entry, _ := facet.(map[string]any)
features, _ := entry["features"].([]any)
for _, feature := range features {
mention, _ := feature.(map[string]any)
if featureType, _ := mention["$type"].(string); featureType != MentionFacetType {
continue
}
mentions++
did, _ := mention["did"].(string)
matched = did == subject
}
}
return mentions == 1 && matched
}
func strongRefOf(value any) (*atproto.StrongRef, bool) {
fields, ok := value.(map[string]any)
if !ok {
return nil, false
}
uri, _ := fields["uri"].(string)
cid, _ := fields["cid"].(string)
if !strings.HasPrefix(uri, "at://") || cid == "" {
return nil, false
}
return &atproto.StrongRef{URI: uri, CID: cid}, true
}
func (r *Resolver) pinnedRecord(ctx context.Context, ref atproto.StrongRef) (map[string]any, string, error) {
record, err := r.client.GetRecordAt(ctx, ref)
if errors.Is(err, atproto.ErrRecordNotFound) {
return nil, "the record no longer resolves", nil
}
if err != nil {
return nil, "", err
}
if record.CID != ref.CID {
return nil, "the record cid changed", nil
}
return record.Value, "", nil
}
func (r *Resolver) deny(reason string, want claim, meta map[string]any) (bool, error) {
fields := map[string]any{"did": want.subject, "operator": want.operator, "service": want.service, "reason": reason}
for key, value := range meta {
fields[key] = value
}
r.log("info", "association denied", fields)
return false, nil
}
func (r *Resolver) proofHeld(ctx context.Context, want claim, proof atproto.StrongRef, assoc associationKey) (bool, error) {
repo, collection, _ := atproto.SplitURI(proof.URI)
kind := KindOfCollection(collection)
meta := map[string]any{"proof": proof.URI, "cid": proof.CID}
switch {
case repo != want.operator:
return r.deny("the proof is not in the authority repo", want, meta)
case kind == "" || !assoc.allows(kind):
return r.deny("the proof kind is not accepted", want, meta)
}
value, reason, err := r.pinnedRecord(ctx, proof)
if err != nil || reason != "" {
if err != nil {
return false, err
}
return r.deny("proof: "+reason, want, meta)
}
if !Matches(kind, value, want.operator, want.subject, want.service, assoc.template) {
return r.deny("the proof does not match", want, meta)
}
if kind == KindBskyPost || kind == KindDelvePost {
if assoc.requireContract {
return r.deny("a post carries no contract", want, meta)
}
return true, nil
}
return r.scopeHeld(ctx, value, want, assoc)
}
func (r *Resolver) associationHeld(ctx context.Context, want claim, assoc associationKey) (bool, error) {
value, err := r.getRecord(ctx, want.operator, AssociationNSID, ClaimRKey(want.service, want.subject))
if err != nil || value == nil {
return false, err
}
if !Matches(KindAssociation, value, want.operator, want.subject, want.service, assoc.template) {
return r.deny("the association record does not match", want, nil)
}
return r.scopeHeld(ctx, value, want, assoc)
}
func (r *Resolver) scopeHeld(ctx context.Context, value map[string]any, want claim, assoc associationKey) (bool, error) {
rawContract, scoped := value["contract"]
rawExpires, expiring := value["expiresAt"]
expiresAt, _ := rawExpires.(string)
switch {
case scoped && expiresAt == "":
return r.deny("a contract-scoped association has no expiresAt", want, nil)
case assoc.requireContract && !scoped:
return r.deny("the verifier requires a contract-scoped association", want, nil)
}
if expiring {
deadline, err := time.Parse(time.RFC3339Nano, expiresAt)
if err != nil {
return r.deny("the expiresAt is not a datetime", want, map[string]any{"expiresAt": expiresAt})
}
if !r.now().Before(deadline) {
return r.deny("the association expired", want, map[string]any{"expiresAt": expiresAt})
}
}
if !scoped {
return true, nil
}
contract, ok := strongRefOf(rawContract)
if !ok {
return r.deny("the contract is not a strongRef", want, nil)
}
return r.contractHeld(ctx, *contract, want)
}
func (r *Resolver) contractHeld(ctx context.Context, contract atproto.StrongRef, want claim) (bool, error) {
meta := map[string]any{"contract": contract.URI, "cid": contract.CID}
repo, collection, _ := atproto.SplitURI(contract.URI)
if repo != want.operator || collection != market.AcceptNSID {
return r.deny("the contract is not a market.accept of the authority", want, meta)
}
accept, reason, err := r.pinnedRecord(ctx, contract)
if err != nil || reason != "" {
if err != nil {
return false, err
}
return r.deny("contract: "+reason, want, meta)
}
bid, ok := strongRefOf(accept["bid"])
if !ok {
return r.deny("the contract names no bid", want, meta)
}
bidder := atproto.RepoFromURI(bid.URI)
if !strings.HasPrefix(bidder, "did:") {
return r.deny("the contract's bid is not in a DID repo", want, meta)
}
receiptURI := "at://" + bidder + "/" + market.ReceiptNSID + "/" + market.ReceiptRKey(contract.URI, contract.CID)
receipt, err := r.client.GetRecordAt(ctx, atproto.StrongRef{URI: receiptURI})
if errors.Is(err, atproto.ErrRecordNotFound) {
return r.deny("the contract has no receipt", want, meta)
}
if err != nil {
return false, err
}
if receipt.URI != receiptURI {
return r.deny("the receipt uri is not canonical", want, map[string]any{"contract": contract.URI, "receipt": receipt.URI})
}
if answered, ok := strongRefOf(receipt.Value["accept"]); !ok || *answered != contract {
return r.deny("the receipt does not answer the contract", want, meta)
}
released, err := r.getRecord(ctx, want.operator, market.ComputeEventsVMDeleteNSID, market.ReleasePayloadRKey(receiptURI))
if err != nil {
return false, err
}
if released != nil {
return r.deny("the contract was released", want, meta)
}
terminationRKey, _ := market.EventRKeys(market.TerminationKey(receiptURI))
terminated, err := r.getRecord(ctx, bidder, market.ComputeEventsVMTerminatedNSID, terminationRKey)
if err != nil {
return false, err
}
if terminated != nil {
return r.deny("the contract was terminated", want, meta)
}
return true, nil
}