Skip to content

Selections

Provides an SSVC selection object and functions to facilitate transition from an SSVC decision point to a selection.

MinimalDecisionPointValue

Bases: _Base, _Keyed, BaseModel

A minimal representation of a decision point value. Intended to parallel the DecisionPointValue object, but with fewer required fields. A decision point value is uniquely identified within a decision point by its key. Globally, the combination of Decision Point namespace, key, and version coupled with the value key uniquely identifies a value across all decision points and values. Other required fields in the DecisionPointValue object, such as name and description, are optional here.

Source code in src/ssvc/selection.py
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
class MinimalDecisionPointValue(_Base, _Keyed, BaseModel):
    """
    A minimal representation of a decision point value.
    Intended to parallel the DecisionPointValue object, but with fewer required fields.
    A decision point value is uniquely identified within a decision point by its key.
    Globally, the combination of Decision Point namespace, key, and version coupled with the value key
    uniquely identifies a value across all decision points and values.
    Other required fields in the DecisionPointValue object, such as name and description, are optional here.
    """

    model_config = ConfigDict(extra="forbid")

    @model_validator(mode="before")
    def set_optional_fields(cls, data):
        if "name" not in data:
            data["name"] = ""
        if "description" not in data:
            data["description"] = ""

        return data

    @model_validator(mode="after")
    def validate_values(cls, data):
        """
        If name or description are empty strings, set them to None so that
        they are not included in the JSON output when serialized using model_dump_json.
        """
        if not data.name:
            data.name = None
        if not data.description:
            data.description = None
        return data

validate_values(data)

If name or description are empty strings, set them to None so that they are not included in the JSON output when serialized using model_dump_json.

Source code in src/ssvc/selection.py
71
72
73
74
75
76
77
78
79
80
81
@model_validator(mode="after")
def validate_values(cls, data):
    """
    If name or description are empty strings, set them to None so that
    they are not included in the JSON output when serialized using model_dump_json.
    """
    if not data.name:
        data.name = None
    if not data.description:
        data.description = None
    return data

Reference

Bases: BaseModel

A reference to a resource that provides additional context about the decision points or selections. This object is intentionally minimal and contains only the URL and an optional description.

Source code in src/ssvc/selection.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
class Reference(BaseModel):
    """
    A reference to a resource that provides additional context about the decision points or selections.
    This object is intentionally minimal and contains only the URL and an optional description.
    """

    model_config = ConfigDict(extra="forbid")

    uri: AnyUrl
    description: str

    # override schema generation to ensure that description is not required
    def model_json_schema(cls, **kwargs):
        schema = super().model_json_schema(**kwargs)
        not_required = ["description"]
        if "required" in schema and isinstance(schema["required"], list):
            # remove description from required list if it exists
            schema["required"] = [
                field for field in schema["required"] if field not in not_required
            ]
        return schema

Selection

Bases: _Valued, _Versioned, _Keyed, _Namespaced, _Base, BaseModel

A minimal selection object that contains the decision point ID and the selected values. While the Selection object parallels the DecisionPoint object, it is intentionally minimal, with fewer required fields and no additional metadata, as it is meant to represent a selection made from a previously defined decision point. The expectation is that a Selection object will usually have fewer values than the original decision point, as it represents a specific evaluation at a specific time and may therefore rule out some values that were previously considered. Other fields like name and description may be copied from the decision point, but are not required.

Source code in src/ssvc/selection.py
 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
class Selection(_Valued, _Versioned, _Keyed, _Namespaced, _Base, BaseModel):
    """
    A minimal selection object that contains the decision point ID and the selected values.
    While the Selection object parallels the DecisionPoint object, it is intentionally minimal, with
    fewer required fields and no additional metadata, as it is meant to represent a selection made from a
    previously defined decision point. The expectation is that a Selection object will usually have
    fewer values than the original decision point, as it represents a specific evaluation
    at a specific time and may therefore rule out some values that were previously considered.
    Other fields like name and description may be copied from the decision point, but are not required.
    """

    model_config = ConfigDict(extra="forbid")

    # _Versioned has a default value, but here we don't want to have a default
    version: VersionString

    values: tuple[MinimalDecisionPointValue, ...] = Field(
        ...,
        description="A list of selected value keys from the decision point values.",
        min_length=1,
        examples=[
            [{"key": "N"}, {"key": "Y"}],
            [{"key": "A"}, {"key": "B"}, {"key": "C"}],
        ],  # Example values
    )

    # class method to convert a decision point to a selection
    @classmethod
    def from_decision_point(
        cls, decision_point: DecisionPoint, include_optional: bool = False
    ) -> "Selection":
        """
        Converts a decision point to a minimal selection object.

        Args:
            decision_point (DecisionPoint): The decision point to convert.

        Returns:
            Selection: The resulting minimal selection object.
        """
        data = {
            "namespace": decision_point.namespace,
            "key": decision_point.key,
            "version": decision_point.version,
            "values": [
                MinimalDecisionPointValue(key=val.key) for val in decision_point.values
            ],
        }
        for attr in ("name", "description"):
            if hasattr(decision_point, attr):
                data[attr] = getattr(decision_point, attr)

        return cls(**data)

    @model_validator(mode="before")
    def set_optional_fields(cls, data):
        if "name" not in data:
            data["name"] = ""
        if "description" not in data:
            data["description"] = ""
        return data

    @model_validator(mode="after")
    def validate_values(cls, data):
        if not data.name:
            data.name = None
        if not data.description:
            data.description = None
        return data

    def model_json_schema(cls, **kwargs):
        schema = super().model_json_schema(**kwargs)
        not_required = ["name", "description"]
        if "required" in schema and isinstance(schema["required"], list):
            # remove description from required list if it exists
            schema["required"] = [
                field for field in schema["required"] if field not in not_required
            ]
        return schema

from_decision_point(decision_point, include_optional=False) classmethod

Converts a decision point to a minimal selection object.

Parameters:

Name Type Description Default
decision_point DecisionPoint

The decision point to convert.

required

Returns:

Name Type Description
Selection Selection

The resulting minimal selection object.

Source code in src/ssvc/selection.py
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
@classmethod
def from_decision_point(
    cls, decision_point: DecisionPoint, include_optional: bool = False
) -> "Selection":
    """
    Converts a decision point to a minimal selection object.

    Args:
        decision_point (DecisionPoint): The decision point to convert.

    Returns:
        Selection: The resulting minimal selection object.
    """
    data = {
        "namespace": decision_point.namespace,
        "key": decision_point.key,
        "version": decision_point.version,
        "values": [
            MinimalDecisionPointValue(key=val.key) for val in decision_point.values
        ],
    }
    for attr in ("name", "description"):
        if hasattr(decision_point, attr):
            data[attr] = getattr(decision_point, attr)

    return cls(**data)

SelectionList

Bases: _Timestamped, BaseModel

A list decision point selections that represent an evaluation at a specific time of evaluation. Individual selections are derived from decision points, and each selection contains a minimal representation of the decision point and the selected values.

A SelectionList requires a timestamp in RFC 3339 format, which indicates when the selections were made.

Optional fields include

  • target_ids: If present, a non-empty list of identifiers for the item or items being evaluated.
  • resources: If present, a non-empty list of references to resources that provide additional context about the decision points found in this selection. Resources point to documentation, JSON files, or other relevant information that describe what the decision points are and how they should be interpreted.
  • references: If present, a non-empty list of references to resources that provide additional context about the specific values selected. References point to reports, advisories, or other relevant information that describe why the selected values were chosen.
Source code in src/ssvc/selection.py
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
class SelectionList(_Timestamped, BaseModel):
    """
    A list decision point selections that represent an evaluation at a specific time of evaluation.
    Individual selections are derived from decision points, and each selection
    contains a minimal representation of the decision point and the selected values.

    A SelectionList requires a timestamp in RFC 3339 format, which indicates when the selections were made.

    Optional fields include

    - `target_ids`: If present, a non-empty list of identifiers for the item or items being evaluated.
    - `resources`: If present, a non-empty list of references to resources that provide additional context about the decision points
        found in this selection. Resources point to documentation, JSON files, or other relevant information that
        describe what the decision points are and how they should be interpreted.
    - `references`: If present, a non-empty list of references to resources that provide additional context about the specific values selected.
        References point to reports, advisories, or other relevant information that describe why the selected values were chosen.
    """

    model_config = ConfigDict(extra="forbid")
    schemaVersion: Literal[SCHEMA_VERSION] = Field(
        ...,
        description="The schema version of this selection list.",
    )

    target_ids: TargetIdList = Field(
        default_factory=list,
        description="Optional list of identifiers for the item or items "
        "(vulnerabilities, reports, advisories, systems, assets, etc.) "
        "being evaluated by these selections.",
        examples=[
            ["CVE-1900-0000"],
            ["VU#999999", "GHSA-0123-4567-89ab"],
        ],
        min_length=1,
    )
    selections: list[Selection] = Field(
        ...,
        description="List of selections made from decision points. Each selection item corresponds to "
        "value keys contained in a specific decision point identified by its namespace, key, and version. "
        "Note that selection objects are deliberately minimal objects and do not contain the full decision point details.",
        min_length=1,
    )
    timestamp: datetime = Field(
        ...,
        description="Timestamp of the selections, in RFC 3339 format.",
        examples=["2025-01-01T12:00:00Z", "2025-01-02T15:30:45-04:00"],
    )
    resources: list[Reference] = Field(
        default_factory=list,
        min_length=1,
        description="A list of references to resources that provide additional context about the decision points found in this selection.",
        examples=[
            [
                {
                    "uri": "https://example.com/decision_points",
                    "description": "Documentation for a set of decision points",
                },
                {
                    "uri": "https://example.org/definitions/dp2.json",
                    "description": "JSON representation of decision point 2",
                },
                {
                    "uri": "https://example.com/ssvc/x_com.example/decision_points.json",
                    "description": "A JSON file containing extension decision points in the x_com.example namespace",
                },
            ],
        ],
    )
    references: list[Reference] = Field(
        default_factory=list,
        min_length=1,
        description="A list of references to resources that provide additional context about the specific values selected.",
        examples=[
            [
                {
                    "uri": "https://example.com/report",
                    "description": "A report on which the selections were based",
                },
            ]
        ],
    )

    @model_validator(mode="before")
    def set_schema_version(cls, data):
        if "schemaVersion" not in data:
            data["schemaVersion"] = SCHEMA_VERSION
        return data

    # target_ids should be a non-empty list if not None
    @field_validator("target_ids", mode="before")
    @classmethod
    def validate_target_ids(cls, value: Optional[list[str]]) -> Optional[list[str]]:
        """
        Validate the target_ids field.
        If target_ids is provided, it must be a non-empty list of strings.
        """
        if value is None:
            return []
        if not isinstance(value, list):
            raise ValueError("target_ids must be a list of strings.")
        if len(value) == 0:
            raise ValueError("target_ids must be a non-empty list of strings.")
        for item in value:
            if not isinstance(item, str):
                raise ValueError("Each target_id must be a string.")
        return value

    def add_selection(self, selection: Selection) -> None:
        """
        Adds a minimal selection to the list.

        Args:
            selection (Selection): The minimal selection to add.
        """
        self.selections.append(selection)

    # override schema generation to ensure it's the way we want it
    @classmethod
    def model_json_schema(cls, **kwargs):
        schema = super().model_json_schema(**kwargs)

        schema["title"] = "Decision Point Value Selection List"
        schema["$schema"] = "https://json-schema.org/draft/2020-12/schema"
        schema["$id"] = (
            "https://certcc.github.io/SSVC/data/schema/v2/Decision_Point_Value_Selection-2-0-0.schema.json"
        )
        schema["description"] = (
            "This schema defines the structure for representing selected values from SSVC Decision Points. "
            "Each selection list can have multiple selection objects, each representing a decision point, and each "
            "selection object can have multiple selected values when full certainty (i.e., a singular value selection) "
            "is not available."
        )

        non_required_fields = [
            "name",
            "description",
            "target_ids",
            "resources",
            "references",
        ]

        # remove non-required fields from the required list
        if "required" in schema and isinstance(schema["required"], list):
            schema["required"] = [
                field
                for field in schema["required"]
                if field not in non_required_fields
            ]

        # dive in to find all the required lists in the schema
        # don't forget the defs
        if "$defs" in schema:
            for prop in schema["$defs"].values():
                if isinstance(prop, dict) and "required" in prop:
                    # remove non-required fields from the required list
                    prop["required"] = [
                        r for r in prop["required"] if r not in non_required_fields
                    ]

        # preferred order of fields, just setting for convention
        preferred_order = [
            "$schema",
            "$id",
            "title",
            "description",
            "schemaVersion",
            "type",
            "$defs",
            "required",
            "properties",
            "additionalProperties",
        ]

        # create a new dict with the preferred order of fields first
        ordered_fields = {k: schema[k] for k in preferred_order if k in schema}
        # add the rest of the fields in their original order
        for k in schema:
            if k not in ordered_fields:
                ordered_fields[k] = schema[k]

        return ordered_fields

add_selection(selection)

Adds a minimal selection to the list.

Parameters:

Name Type Description Default
selection Selection

The minimal selection to add.

required
Source code in src/ssvc/selection.py
295
296
297
298
299
300
301
302
def add_selection(self, selection: Selection) -> None:
    """
    Adds a minimal selection to the list.

    Args:
        selection (Selection): The minimal selection to add.
    """
    self.selections.append(selection)

validate_target_ids(value) classmethod

Validate the target_ids field. If target_ids is provided, it must be a non-empty list of strings.

Source code in src/ssvc/selection.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
@field_validator("target_ids", mode="before")
@classmethod
def validate_target_ids(cls, value: Optional[list[str]]) -> Optional[list[str]]:
    """
    Validate the target_ids field.
    If target_ids is provided, it must be a non-empty list of strings.
    """
    if value is None:
        return []
    if not isinstance(value, list):
        raise ValueError("target_ids must be a list of strings.")
    if len(value) == 0:
        raise ValueError("target_ids must be a non-empty list of strings.")
    for item in value:
        if not isinstance(item, str):
            raise ValueError("Each target_id must be a string.")
    return value

main()

Prints example selections and their schema in JSON format.

Returns:

Type Description
None

None

Source code in src/ssvc/selection.py
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
def main() -> None:
    """
    Prints example selections and their schema in JSON format.

    Returns:
        None
    """
    from ssvc.decision_points.ssvc.automatable import LATEST as dp1
    from ssvc.decision_points.ssvc.safety_impact import LATEST as dp2
    import json

    a1 = Selection.from_decision_point(dp1)
    a2 = Selection.from_decision_point(dp2)
    selections = SelectionList(
        schemaVersion=SCHEMA_VERSION,
        selections=[a1, a2],
        timestamp=datetime.now(),
        target_ids=["CVE-1900-0001", "GHSA-0123-4567-89ab"],
        references=[
            Reference(
                uri="https://example.com/report",
                description="A report on which the selections were based",
            )
        ],
    )

    print(selections.model_dump_json(indent=2, exclude_none=True, exclude_unset=True))

    print("# Schema for SelectionList")
    schema = SelectionList.model_json_schema()

    print(json.dumps(schema, indent=2))

    # find local path to this file
    import os

    current_dir = os.path.dirname(os.path.abspath(__file__))
    # construct the path to the schema file
    schema_path = (
        "../../data/schema/v2/Decision_Point_Value_Selection-2-0-0.schema.json"
    )
    schema_path = os.path.abspath(os.path.join(current_dir, schema_path))

    with open(schema_path, "w") as f:
        print(f"Writing schema to {schema_path}")
        json.dump(schema, f, indent=2)
        f.write("\n")  # Ensure the file ends with a newline