Debian Codegraph @

iri.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "net/url"
9 "path/filepath"
10 "slices"
11 "strings"
12
13 "github.com/go-ap/errors"
14 "github.com/valyala/fastjson"
15 )
16
17 const (
18 // ActivityBaseURI the URI for the ActivityStreams namespace
19 ActivityBaseURI = IRI("https://www.w3.org/ns/activitystreams")
20 // SecurityContextURI the URI for the security namespace (for an Actor's PublicKey)
21 SecurityContextURI = IRI("https://w3id.org/security/v1")
22 // PublicNS is the reference to the Public entity in the ActivityStreams namespace.
23 //
24 // Public Addressing
25 //
26 // https://www.w3.org/TR/activitypub/#public-addressing
27 //
28 // In addition to [ActivityStreams] collections and objects, Activities may additionally be addressed to the
29 // special "public" collection, with the identifier https://www.w3.org/ns/activitystreams#Public. For example:
30 //
31 // {
32 // "@context": "https://www.w3.org/ns/activitystreams",
33 // "id": "https://www.w3.org/ns/activitystreams#Public",
34 // "type": "Collection"
35 // }
36 // Activities addressed to this special URI shall be accessible to all users, without authentication.
37 // Implementations MUST NOT deliver to the "public" special collection; it is not capable of receiving
38 // actual activities. However, actors MAY have a sharedInbox endpoint which is available for efficient
39 // shared delivery of public posts (as well as posts to followers-only); see 7.1.3 Shared Inbox Delivery.
40 //
41 // NOTE
42 // Compacting an ActivityStreams object using the ActivityStreams JSON-LD context might result in
43 // https://www.w3.org/ns/activitystreams#Public being represented as simply Public or as:Public which are valid
44 // representations of the Public collection. Implementations which treat ActivityStreams objects as simply JSON
45 // rather than converting an incoming activity over to a local context using JSON-LD tooling should be aware
46 // of this and should be prepared to accept all three representations.
47 PublicNS = ActivityBaseURI + "#Public"
48 )
49
50 // JsonLDContext is a slice of IRIs that form the default context for the objects in the
51 // GoActivitypub vocabulary.
52 // It does not represent just the default ActivityStreams public namespace, but it also
53 // has the W3 Permanent Identifier Community Group's Security namespace, which appears
54 // in the Actor type objects, which contain public key related data.
55 var JsonLDContext = []IRI{
56 ActivityBaseURI,
57 SecurityContextURI,
58 }
59
60 type (
61 // IRI is a Internationalized Resource Identifiers (IRIs) RFC3987
62 IRI string
63 IRIs []IRI
64 )
65
66 func (i IRI) Format(s fmt.State, verb rune) {
67 switch verb {
68 case 's', 'v':
69 _, _ = io.WriteString(s, i.String())
70 }
71 }
72
73 // String returns the String value of the IRI object
74 func (i IRI) String() string {
75 return string(i)
76 }
77
78 // GetLink
79 func (i IRI) GetLink() IRI {
80 return i
81 }
82
83 // URL
84 func (i IRI) URL() (*url.URL, error) {
85 if i == "" {
86 return nil, errors.Newf("empty IRI")
87 }
88 return url.Parse(string(i))
89 }
90
91 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
92 func (i *IRI) UnmarshalJSON(s []byte) error {
93 *i = IRI(strings.Trim(string(s), "\""))
94 return nil
95 }
96
97 // MarshalJSON encodes the receiver object to a JSON document.
98 func (i IRI) MarshalJSON() ([]byte, error) {
99 if i == "" {
100 return nil, nil
101 }
102 b := make([]byte, 0)
103 JSONWrite(&b, '"')
104 JSONWriteS(&b, i.String())
105 JSONWrite(&b, '"')
106 return b, nil
107 }
108
109 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
110 func (i *IRI) UnmarshalBinary(data []byte) error {
111 return i.GobDecode(data)
112 }
113
114 // MarshalBinary implements the encoding.BinaryMarshaler interface.
115 func (i IRI) MarshalBinary() ([]byte, error) {
116 return i.GobEncode()
117 }
118
119 // GobEncode
120 func (i IRI) GobEncode() ([]byte, error) {
121 return []byte(i), nil
122 }
123
124 // GobEncode
125 func (i IRIs) GobEncode() ([]byte, error) {
126 if len(i) == 0 {
127 return []byte{}, nil
128 }
129 b := bytes.Buffer{}
130 gg := gob.NewEncoder(&b)
131 bb := make([][]byte, 0)
132 for _, iri := range i {
133 bb = append(bb, []byte(iri))
134 }
135 if err := gg.Encode(bb); err != nil {
136 return nil, err
137 }
138 return b.Bytes(), nil
139 }
140
141 // GobDecode
142 func (i *IRI) GobDecode(data []byte) error {
143 *i = IRI(data)
144 return nil
145 }
146
147 func (i *IRIs) GobDecode(data []byte) error {
148 if len(data) == 0 {
149 // NOTE(marius): this behaviour diverges from vanilla gob package
150 return nil
151 }
152 err := gob.NewDecoder(bytes.NewReader(data)).Decode(i)
153 if err == nil {
154 return nil
155 }
156 bb := make([][]byte, 0)
157 err = gob.NewDecoder(bytes.NewReader(data)).Decode(&bb)
158 if err != nil {
159 return err
160 }
161 for _, b := range bb {
162 *i = append(*i, IRI(b))
163 }
164 return nil
165 }
166
167 // AddPath concatenates el elements as a path to i
168 func (i IRI) AddPath(el ...string) IRI {
169 iri := strings.TrimRight(i.String(), "/")
170 return IRI(iri + filepath.Clean(filepath.Join("/", filepath.Join(el...))))
171 }
172
173 // GetID
174 func (i IRI) GetID() ID {
175 return i
176 }
177
178 // GetType
179 func (i IRI) GetType() Typer {
180 return IRIType
181 }
182
183 // Match returns whether the receiver matches the ActivityVocabularyType arguments.
184 func (i IRI) Match(tt ...ActivityVocabularyType) bool {
185 return ActivityVocabularyTypes(tt).Match(i.GetType())
186 }
187
188 // IsLink
189 func (i IRI) IsLink() bool {
190 return true
191 }
192
193 // IsObject
194 func (i IRI) IsObject() bool {
195 return false
196 }
197
198 // IsCollection returns false for IRI objects
199 func (i IRI) IsCollection() bool {
200 return false
201 }
202
203 // FlattenToIRI checks if Item can be flatten to an IRI and returns it if so
204 func FlattenToIRI(it Item) Item {
205 if !IsNil(it) && it.IsObject() && len(it.GetLink()) > 0 {
206 return it.GetLink()
207 }
208 return it
209 }
210
211 func (i IRIs) MarshalJSON() ([]byte, error) {
212 if len(i) == 0 {
213 return []byte{'[', ']'}, nil
214 }
215 b := make([]byte, 0)
216 writeCommaIfNotEmpty := func(notEmpty bool) {
217 if notEmpty {
218 JSONWriteS(&b, ",")
219 }
220 }
221 JSONWrite(&b, '[')
222 for k, iri := range i {
223 writeCommaIfNotEmpty(k > 0)
224 JSONWrite(&b, '"')
225 JSONWriteS(&b, iri.String())
226 JSONWrite(&b, '"')
227 }
228 JSONWrite(&b, ']')
229 return b, nil
230 }
231
232 func (i *IRIs) UnmarshalJSON(data []byte) error {
233 if i == nil {
234 return nil
235 }
236 p := fastjson.Parser{}
237 val, err := p.ParseBytes(data)
238 if err != nil {
239 return err
240 }
241 switch val.Type() {
242 case fastjson.TypeString:
243 if iri, ok := asIRI(val); ok && len(iri) > 0 {
244 *i = append(*i, iri)
245 }
246 case fastjson.TypeArray:
247 for _, v := range val.GetArray() {
248 if iri, ok := asIRI(v); ok && len(iri) > 0 {
249 *i = append(*i, iri)
250 }
251 }
252 }
253 return nil
254 }
255
256 // GetID returns the ID corresponding to ItemCollection
257 func (i IRIs) GetID() ID {
258 return EmptyID
259 }
260
261 // GetLink returns the empty IRI
262 func (i IRIs) GetLink() IRI {
263 return EmptyIRI
264 }
265
266 // GetType returns the ItemCollection's types
267 func (i IRIs) GetType() Typer {
268 return CollectionOfIRIs
269 }
270
271 // IsLink returns false for an ItemCollection object
272 func (i IRIs) IsLink() bool {
273 return false
274 }
275
276 // IsObject returns true for a ItemCollection object
277 func (i IRIs) IsObject() bool {
278 return false
279 }
280
281 // IsCollection returns true for IRI slices
282 func (i IRIs) IsCollection() bool {
283 return true
284 }
285
286 // Append facilitates adding elements to the IRIs slices
287 func (i *IRIs) Append(items ...Item) error {
288 for _, it := range items {
289 if IsNil(it) {
290 continue
291 }
292 if (*i).Contains(it.GetLink()) {
293 continue
294 }
295 *i = append(*i, it.GetLink())
296 }
297 return nil
298 }
299
300 // Remove removes the items from the IRIs slice
301 func (i *IRIs) Remove(it ...Item) {
302 items := ItemCollection(it)
303 *i = slices.DeleteFunc(*i, func(iri IRI) bool {
304 return items.Contains(iri)
305 })
306 }
307
308 func (i *IRIs) Collection() ItemCollection {
309 res := make(ItemCollection, len(*i))
310 for k, iri := range *i {
311 res[k] = iri
312 }
313 return res
314 }
315
316 func (i *IRIs) Count() uint {
317 return uint(len(*i))
318 }
319
320 // Contains verifies if IRIs array contains the received one
321 func (i IRIs) Contains(r Item) bool {
322 if len(i) == 0 {
323 return false
324 }
325 for _, iri := range i {
326 if r.GetLink().Equals(iri, false) {
327 return true
328 }
329 }
330 return false
331 }
332
333 func validURL(u *url.URL, checkScheme bool) bool {
334 if u == nil {
335 return false
336 }
337 if len(u.Host) == 0 {
338 return false
339 }
340 if checkScheme {
341 return len(u.Scheme) > 0
342 }
343 return true
344 }
345
346 func stripFragment(u string) string {
347 p := strings.Index(u, "#")
348 if p <= 0 {
349 p = len(u)
350 }
351 return u[:p]
352 }
353
354 func stripScheme(u string) string {
355 p := strings.Index(u, "://")
356 if p < 0 {
357 p = 0
358 }
359 return u[p:]
360 }
361
362 func irisEqual(i1, i2 IRI, checkScheme bool) bool {
363 u, e := i1.URL()
364 uw, ew := i2.URL()
365 if e != nil || ew != nil || !validURL(u, checkScheme) || !validURL(uw, checkScheme) {
366 return strings.EqualFold(i1.String(), i2.String())
367 }
368 if checkScheme {
369 if !strings.EqualFold(u.Scheme, uw.Scheme) {
370 return false
371 }
372 }
373 if !strings.EqualFold(u.Host, uw.Host) {
374 return false
375 }
376 if u.Path == "" {
377 u.Path = "/"
378 }
379 if uw.Path == "" {
380 uw.Path = "/"
381 }
382 if !strings.EqualFold(filepath.Clean(u.Path), filepath.Clean(uw.Path)) {
383 return false
384 }
385 uq := u.Query()
386 uwq := uw.Query()
387 if len(uq) != len(uwq) {
388 return false
389 }
390 for k, uqv := range uq {
391 uwqv, ok := uwq[k]
392 if !ok {
393 return false
394 }
395 if len(uqv) != len(uwqv) {
396 return false
397 }
398 for _, uqvv := range uqv {
399 eq := false
400 for _, uwqvv := range uwqv {
401 if uwqvv == uqvv {
402 eq = true
403 continue
404 }
405 }
406 if !eq {
407 return false
408 }
409 }
410 }
411 return true
412 }
413
414 // Equal verifies if our receiver IRI is equals with the "with" IRI with strict protocol check
415 func (i IRI) Equal(with IRI) bool {
416 return i.Equals(with, true)
417 }
418
419 // Equals verifies if our receiver IRI is equals with the "with" IRI
420 func (i IRI) Equals(with IRI, checkScheme bool) bool {
421 is := stripFragment(string(i))
422 ws := stripFragment(string(with))
423 if !checkScheme {
424 is = stripScheme(is)
425 ws = stripScheme(ws)
426 }
427 if strings.EqualFold(is, ws) {
428 return true
429 }
430 return irisEqual(i, with, checkScheme)
431 }
432
433 func hostSplit(h string) (string, string) {
434 pieces := strings.Split(h, ":")
435 if len(pieces) == 0 {
436 return "", ""
437 }
438 if len(pieces) == 1 {
439 return pieces[0], ""
440 }
441 return pieces[0], pieces[1]
442 }
443
444 func (i IRI) Contains(what IRI, checkScheme bool) bool {
445 u, e := i.URL()
446 uw, ew := what.URL()
447 if e != nil || ew != nil {
448 return strings.Contains(i.String(), what.String())
449 }
450 if checkScheme {
451 if u.Scheme != uw.Scheme {
452 return false
453 }
454 }
455 uHost, _ := hostSplit(u.Host)
456 uwHost, _ := hostSplit(uw.Host)
457 if uHost != uwHost {
458 return false
459 }
460 p := u.Path
461 if p != "" {
462 p = filepath.Clean(p)
463 } else {
464 p = "/"
465 }
466 pw := uw.Path
467 if pw != "" {
468 pw = filepath.Clean(pw)
469 } else {
470 pw = "/"
471 }
472 return strings.Contains(p, pw)
473 }
474
475 func (i IRI) ItemsMatch(col ...Item) bool {
476 for _, it := range col {
477 if match := it.GetLink().Contains(i, false); !match {
478 return false
479 }
480 }
481 return true
482 }
483
484 // OnIRIs calls function fn on it Item if it can be asserted to type IRIs
485 //
486 // It should be used when Item represents an IRI slice.
487 func OnIRIs(it Item, fn WithIRIsFn) error {
488 if it == nil {
489 return nil
490 }
491 col, err := ToIRIs(it)
492 if err != nil {
493 return err
494 }
495 return fn(col)
496 }