-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.go
More file actions
497 lines (476 loc) · 17.3 KB
/
Copy pathjson.go
File metadata and controls
497 lines (476 loc) · 17.3 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package sdk
import (
"encoding/json"
"fmt"
"path"
"sort"
"strings"
)
// nodeWire is the flat protocol-v1 node payload: the legacy field set plus
// the additive kind discriminator, origins list, and declaring manifest
// path. Struct tags are the wire contract; every addition is omitempty.
type nodeWire struct {
Kind NodeKind `json:"kind,omitempty"`
ID string `json:"id"`
PURL string `json:"purl,omitempty"`
Ecosystem Ecosystem `json:"ecosystem,omitempty"`
PackageManager PackageManager `json:"package_manager,omitempty"`
Type PackageType `json:"type,omitempty"`
Org string `json:"org,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Language Language `json:"language,omitempty"`
FirstParty bool `json:"first_party,omitempty"`
Relationship DependencyRelationship `json:"relationship,omitempty"`
Source DependencySource `json:"source,omitempty"`
Scopes []Scope `json:"scopes,omitempty"`
Locations []PackageLocation `json:"locations,omitempty"`
CPEs []string `json:"cpes,omitempty"`
Digests []Digest `json:"digests,omitempty"`
Copyright string `json:"copyright,omitempty"`
FoundBy string `json:"found_by,omitempty"`
ResolvedURL string `json:"resolved_url,omitempty"`
Origin *DependencyOrigin `json:"origin,omitempty"`
Origins []DependencyOrigin `json:"origins,omitempty"`
Licenses []PackageLicense `json:"licenses,omitempty"`
ExternalReferences []ExternalReference `json:"external_references,omitempty"`
Description string `json:"description,omitempty"`
Homepage string `json:"homepage,omitempty"`
Supplier *Contact `json:"supplier,omitempty"`
Originator *Contact `json:"originator,omitempty"`
DeclaringManifestPath string `json:"declaring_manifest_path,omitempty"`
ManifestKind ManifestKind `json:"manifest_kind,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Matched bool `json:"matched,omitempty"`
PackageRef string `json:"package_ref,omitempty"`
}
// wireKind resolves the node kind of a payload: an explicit kind is
// authoritative and wins over the legacy fields; a payload without one —
// every pre-union binary — infers deterministically: a manifest package
// type is a manifest, the first-party marker is a module, and everything
// else — including an application-typed component without the marker — is
// a dependency (application type alone is never an ownership signal,
// ADR-0015). An unrecognized kind is a decode error, never a guess.
func (w *nodeWire) wireKind() (NodeKind, error) {
if w.Kind != "" {
return ParseNodeKind(string(w.Kind))
}
if strings.EqualFold(strings.TrimSpace(string(w.Type)), string(PackageTypeManifest)) {
return NodeKindManifest, nil
}
if w.FirstParty {
return NodeKindModule, nil
}
return NodeKindDependency, nil
}
// wireOrigins unions the legacy singular origin field with the additive
// origins list, deduplicated by normalized value, so a payload carrying
// both never drops or double-counts origin evidence.
func (w *nodeWire) wireOrigins() []DependencyOrigin {
var singular []DependencyOrigin
if w.Origin != nil {
singular = []DependencyOrigin{*w.Origin}
}
return MergeOrigins(singular, w.Origins)
}
// decodeNode reconstructs a typed node from its wire form through the
// constructor gates. The gates are strict: a dependency payload whose
// identity cannot mint a well-formed package URL is a decode error — the
// wire carries only valid identities, custom purl types included.
func (w *nodeWire) decodeNode() (GraphNode, error) {
kind, err := w.wireKind()
if err != nil {
return nil, err
}
switch kind {
case NodeKindManifest:
return w.decodeManifestNode()
case NodeKindModule:
return w.decodeModuleNode()
default:
return w.decodeDependencyNode()
}
}
func (w *nodeWire) manifestPath() string {
if trimmed := strings.TrimPrefix(w.ID, manifestIDPrefix); trimmed != w.ID && strings.TrimSpace(trimmed) != "" {
return trimmed
}
if w.DeclaringManifestPath != "" {
return w.DeclaringManifestPath
}
for _, location := range w.Locations {
if strings.TrimSpace(location.RealPath) != "" {
return location.RealPath
}
}
return w.Name
}
func (w *nodeWire) decodeManifestNode() (*ManifestNode, error) {
node, err := NewManifestNode(w.manifestPath(), w.ManifestKind)
if err != nil {
return nil, fmt.Errorf("decode manifest node %q: %w", w.ID, err)
}
node.Metadata = w.Metadata
return node, nil
}
func (w *nodeWire) decodeModuleNode() (*ModuleNode, error) {
declaring := w.DeclaringManifestPath
if declaring == "" {
for _, location := range w.Locations {
if strings.TrimSpace(location.RealPath) != "" {
declaring = location.RealPath
break
}
}
}
if declaring == "" {
return nil, fmt.Errorf("decode module node %q: no declaring manifest path", w.ID)
}
node, err := NewModuleNode(declaring, w.coordinates())
if err != nil {
return nil, fmt.Errorf("decode module node %q: %w", w.ID, err)
}
node.Locations = w.Locations
node.Metadata = w.Metadata
return node, nil
}
func (w *nodeWire) decodeDependencyNode() (*DependencyNode, error) {
node, err := newDependencyNode(w.coordinates(), strings.TrimSpace(w.PURL))
if err != nil {
return nil, fmt.Errorf("decode dependency node %q: %w", w.ID, err)
}
node.Relationship = w.Relationship
node.Source = w.Source
node.Scopes = w.Scopes
node.Locations = w.Locations
node.CPEs = w.CPEs
// Routed through the set merge so a digest the codec rejected does not
// survive as a zero element that re-encodes to an empty checksum record.
node.Digests = mergeDigestSet(nil, w.Digests)
node.Copyright = w.Copyright
node.FoundBy = w.FoundBy
node.ResolvedURL = w.ResolvedURL
node.Origins = MergeOrigins(node.Origins, w.wireOrigins())
// MergeLicenses re-runs each claim's gate, so a payload that reached the
// slice without passing through PackageLicense's codec — a hand-built
// value, or one an older producer wrote — is still held to it here.
node.Licenses = MergeLicenses(nil, w.Licenses)
node.ExternalReferences = MergeExternalReferences(nil, w.ExternalReferences)
node.Description = NormalizeDescription(w.Description)
node.Homepage = NormalizeHomepage(w.Homepage)
// normalizedContact returns nil for a contact the codec rejected, so a
// payload like {"kind":"organization"} with no name does not leave a
// non-nil pointer to a zero value that re-encodes as "supplier":{}.
node.Supplier = normalizedContact(w.Supplier)
node.Originator = normalizedContact(w.Originator)
if len(w.Metadata) > 0 {
if node.Metadata == nil {
node.Metadata = make(map[string]any, len(w.Metadata))
}
for key, value := range w.Metadata {
node.Metadata[key] = value
}
}
node.Matched = w.Matched
node.PackageRef = w.PackageRef
return node, nil
}
func (w *nodeWire) coordinates() Coordinates {
return Coordinates{
PURL: w.PURL,
Ecosystem: w.Ecosystem,
PackageManager: w.PackageManager,
Type: w.Type,
Org: w.Org,
Name: w.Name,
Version: w.Version,
Language: w.Language,
}
}
// encodeNodeWire renders a typed node into the flat wire form, dual-writing
// the legacy markers pre-union readers key on: manifest nodes emit the
// manifest package type, module nodes emit the first-party marker, and
// dependency nodes emit the legacy singular origin beside the origins list.
func encodeNodeWire(node GraphNode) nodeWire {
switch n := node.(type) {
case *ManifestNode:
return nodeWire{
Kind: NodeKindManifest,
ID: n.NodeID(),
Type: PackageTypeManifest,
Name: path.Base(n.Path),
ManifestKind: n.FileKind,
Locations: n.NodeLocations(),
Metadata: n.Metadata,
}
case *ModuleNode:
return nodeWire{
Kind: NodeKindModule,
ID: n.NodeID(),
PURL: n.PURL(),
Ecosystem: n.Ecosystem,
PackageManager: n.PackageManager,
Type: n.Type,
Org: n.Org,
Name: n.Name,
Version: n.Version,
Language: n.Language,
FirstParty: true,
DeclaringManifestPath: n.DeclaringManifestPath,
Locations: n.Locations,
Metadata: n.Metadata,
}
case *DependencyNode:
wire := nodeWire{
Kind: NodeKindDependency,
ID: n.NodeID(),
PURL: n.Coordinates.PURL,
Ecosystem: n.Ecosystem,
PackageManager: n.PackageManager,
Type: n.Type,
Org: n.Org,
Name: n.Name,
Version: n.Version,
Language: n.Language,
Relationship: n.Relationship,
Source: n.Source,
Scopes: n.Scopes,
Locations: n.Locations,
CPEs: n.CPEs,
Digests: mergeDigestSet(nil, n.Digests),
Copyright: n.Copyright,
FoundBy: n.FoundBy,
ResolvedURL: n.ResolvedURL,
Origins: n.Origins,
Metadata: n.Metadata,
Matched: n.Matched,
PackageRef: n.PackageRef,
// Re-gated on the way out as well as in, so a field set directly
// on a hand-built node never reaches a reader unchecked.
Licenses: MergeLicenses(nil, n.Licenses),
ExternalReferences: MergeExternalReferences(nil, n.ExternalReferences),
Description: NormalizeDescription(n.Description),
Homepage: NormalizeHomepage(n.Homepage),
Supplier: normalizedContact(n.Supplier),
Originator: normalizedContact(n.Originator),
}
if len(n.Origins) > 0 {
legacy := n.Origins[0]
wire.Origin = &legacy
}
return wire
default:
return nodeWire{}
}
}
// MarshalJSON encodes a dependency node in its flat wire form.
func (n *DependencyNode) MarshalJSON() ([]byte, error) {
wire := encodeNodeWire(n)
return json.Marshal(wire)
}
// UnmarshalJSON decodes a dependency node through the constructor gates. A
// payload of a different node kind, or one whose identity cannot mint a
// well-formed package URL, is an error.
func (n *DependencyNode) UnmarshalJSON(data []byte) error {
var wire nodeWire
if err := json.Unmarshal(data, &wire); err != nil {
return err
}
kind, err := wire.wireKind()
if err != nil {
return err
}
if kind != NodeKindDependency {
return fmt.Errorf("expected a dependency node, got kind %q", kind)
}
decoded, err := wire.decodeDependencyNode()
if err != nil {
return err
}
*n = *decoded
return nil
}
type graphJSON struct {
Nodes []nodeWire `json:"nodes,omitempty"`
Edges []DependencyEdge `json:"edges,omitempty"`
}
// DependencyEdge captures one directed relationship between node IDs.
//
// Kind is additive and omitted when unknown, so a payload written before the
// field keeps its exact bytes. On decode an absent kind is derived from the
// nodes the edge joins, which is why adding the field did not need a wire
// break: the structure already carried the answer.
type DependencyEdge struct {
FromID string `json:"fromId"`
ToID string `json:"toId"`
Kind EdgeKind `json:"kind,omitempty"`
}
// MarshalJSON encodes a graph as a stable transport-friendly adjacency list.
func (g *Graph) MarshalJSON() ([]byte, error) {
if g == nil {
return []byte("null"), nil
}
payload := graphJSON{
Nodes: make([]nodeWire, 0, g.Size()),
}
g.WalkNodes(func(node GraphNode) bool {
payload.Nodes = append(payload.Nodes, encodeNodeWire(node))
return true
})
g.WalkTypedEdges(func(from, to GraphNode, kind EdgeKind) bool {
edge := DependencyEdge{FromID: from.NodeID(), ToID: to.NodeID()}
// The kind is written only when the structure does not already imply
// it. A decoder derives an absent kind from the nodes, so writing a
// derived value would add bytes that say nothing -- and would change
// every existing payload, which is exactly what an additive field must
// not do. What survives here is a kind that contradicts derivation,
// which is the only kind a reader could not reconstruct.
if kind != DeriveEdgeKind(from, to) {
edge.Kind = kind
}
payload.Edges = append(payload.Edges, edge)
return true
})
return json.Marshal(payload)
}
// UnmarshalJSON decodes a graph from the plugin transport adjacency list.
// Nodes are reconstructed through the constructor gates (strict: an invalid
// dependency identity fails the decode) and inserted with fold-by-identity
// semantics, so a legacy payload whose distinct wire IDs mint one canonical
// identity folds instead of erroring. Edges follow the wire-ID → identity
// mapping; an edge that becomes a self-edge after folding is dropped — the
// fold made it meaningless.
func (g *Graph) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
*g = *New()
return nil
}
var payload graphJSON
if err := json.Unmarshal(data, &payload); err != nil {
return err
}
out := NewWithCapacity(len(payload.Nodes))
idMapping := make(map[string]string, len(payload.Nodes))
selfAliases := make([]string, 0, len(payload.Nodes))
for i := range payload.Nodes {
wire := &payload.Nodes[i]
node, err := wire.decodeNode()
if err != nil {
return err
}
survivor, err := out.InsertNode(node)
if err != nil {
return err
}
if wire.ID != "" {
// Two payload nodes reusing one wire ID while minting different
// identities make every edge referencing it order-dependent.
// The pre-union decoder rejected duplicate graph IDs outright;
// this keeps that guarantee where it still means something.
if previous, seen := idMapping[wire.ID]; seen && previous != survivor.NodeID() {
return fmt.Errorf("%w: wire id %q maps to both %q and %q", ErrNodeAlreadyExist, wire.ID, previous, survivor.NodeID())
}
idMapping[wire.ID] = survivor.NodeID()
}
selfAliases = append(selfAliases, survivor.NodeID())
}
// Canonical self-aliases fill gaps only: a wire ID a payload actually
// used always wins. Otherwise a node whose arbitrary wire ID happens to
// equal another node's newly minted identity would have its edges
// silently redirected to that other node, and reversing the node order
// would change the result.
for _, alias := range selfAliases {
if _, claimed := idMapping[alias]; !claimed {
idMapping[alias] = alias
}
}
for _, edge := range payload.Edges {
fromID, okFrom := idMapping[edge.FromID]
toID, okTo := idMapping[edge.ToID]
if !okFrom || !okTo {
return fmt.Errorf("%w: edge %q -> %q", ErrNodeNotFound, edge.FromID, edge.ToID)
}
if fromID == toID {
continue
}
if err := out.AddTypedEdge(fromID, toID, edge.Kind); err != nil {
return err
}
}
*g = *out
return nil
}
// MarshalJSON encodes a package registry as a stable PURL-keyed object for
// plugin transport.
func (r *PackageRegistry) MarshalJSON() ([]byte, error) {
if r == nil {
return []byte("null"), nil
}
payload := make(map[string]*Package, r.Len())
for _, pkg := range r.All() {
if pkg == nil || pkg.PURL == "" {
continue
}
// Package's own codec re-gates each record as it is written, so a
// value installed after insertion -- Ensure, Get, and All all hand
// back mutable pointers -- cannot cross the wire unchecked. The gate
// lives on the type rather than here because package updates on a
// matcher result never pass through this registry at all.
//
// No defensive copy: that codec has a value receiver, so it
// normalizes its own copy and cannot rewrite the stored record. A
// clone here would deep-copy every package on every marshal to
// prevent something that can no longer happen.
payload[pkg.PURL] = pkg
}
return json.Marshal(payload)
}
// UnmarshalJSON decodes a PURL-keyed package registry from plugin transport.
func (r *PackageRegistry) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
*r = *NewPackageRegistry()
return nil
}
payload := map[string]*Package{}
if err := json.Unmarshal(data, &payload); err != nil {
return err
}
out := NewPackageRegistry()
purls := make([]string, 0, len(payload))
for purl := range payload {
purls = append(purls, purl)
}
sort.Strings(purls)
for _, purl := range purls {
pkg := payload[purl]
if pkg == nil {
pkg = &Package{}
}
clone := pkg.Clone()
clone.PURL = purl
out.Add(clone)
}
*r = *out
return nil
}
// MarshalJSON encodes a package manager by its canonical name.
func (p PackageManager) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Name())
}
// UnmarshalJSON decodes a package manager from its canonical name.
func (p *PackageManager) UnmarshalJSON(data []byte) error {
var value string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
if value == "" {
*p = PackageManagerUnknown
return nil
}
manager, err := ParsePackageManager(value)
if err != nil {
return fmt.Errorf("parse package manager: %w", err)
}
*p = manager
return nil
}