Skip to content

trestle.tasks.xlsx_to_oscal_poam

trestle.tasks.xlsx_to_oscal_poam ¤

Transform POAM spreadsheet to OSCAL POAM JSON format.

Attributes¤

logger = logging.getLogger(__name__) module-attribute ¤

Classes¤

PoamBuilder ¤

Builder class for constructing OSCAL POAM objects from spreadsheet data.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
class PoamBuilder:
    """Builder class for constructing OSCAL POAM objects from spreadsheet data."""

    def __init__(self, timestamp: str, validator: PoamValidator) -> None:
        """
        Initialize builder.

        Args:
            timestamp: ISO timestamp for metadata
            validator: PoamValidator instance
        """
        self._timestamp = timestamp
        self._validator = validator

    def create_poam_item(self, poam_id: str, row_data: Dict[str, Any]) -> PoamItem:
        """
        Create PoamItem from row data.

        Args:
            poam_id: POAM ID
            row_data: Row data dictionary

        Returns:
            PoamItem object
        """
        # Required fields
        title = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_NAME, ''))
        description = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_DESCRIPTION, ''))

        # Optional fields
        comments = row_data.get(PoamXlsxHelper.COMMENTS)
        if comments and isinstance(comments, str):
            comments = comments.strip() or None

        # Build properties
        props = []

        # Add POAM ID as property (clean it first)
        clean_poam_id = _safe_strip(poam_id) if poam_id else poam_id
        if clean_poam_id:
            props.append(
                Property(name='poam-id', value=clean_poam_id, uuid=None, ns=None, **{'class': None}, group=None)
            )

        # Add control IDs as properties
        controls_str = row_data.get(PoamXlsxHelper.CONTROLS, '')
        if controls_str:
            controls = self._validator.parse_controls(controls_str)
            for ctrl_id in controls:
                props.append(
                    Property(name='control-id', value=ctrl_id, uuid=None, ns=None, **{'class': None}, group=None)
                )

        # Create PoamItem
        poam_item = PoamItem(
            uuid=UUIDManager.poam_item_uuid(poam_id),
            title=title,
            description=description,
            props=props or None,
            links=None,
            origins=None,
            **{'related-findings': None, 'related-observations': None, 'related-risks': None},
        )

        # Add remarks if present
        if comments:
            poam_item.remarks = comments

        return poam_item

    def create_observation(self, poam_id: str, row_data: Dict[str, Any], helper: PoamXlsxHelper) -> Observation:
        """
        Create Observation from row data.

        Args:
            poam_id: POAM ID
            row_data: Row data dictionary
            helper: PoamXlsxHelper instance

        Returns:
            Observation object
        """
        weakness_name = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_NAME, ''))

        # Description is required
        description = f'Weakness detected: {weakness_name}'
        weakness_source_id = row_data.get(PoamXlsxHelper.WEAKNESS_SOURCE_IDENTIFIER)
        if weakness_source_id and isinstance(weakness_source_id, str):
            weakness_source_id = weakness_source_id.strip()
            if weakness_source_id:
                description += f' (Source: {weakness_source_id})'

        # Collected date (required)
        detection_date_value = row_data.get(PoamXlsxHelper.ORIGINAL_DETECTION_DATE)
        collected = helper.parse_date(detection_date_value)
        if collected is None:
            # Default to current timestamp if no date provided
            collected = datetime.datetime.fromisoformat(self._timestamp)

        # Methods are required
        methods = ['TEST']

        # Origins are optional
        origins = None
        detector_source = row_data.get(PoamXlsxHelper.WEAKNESS_DETECTOR_SOURCE)
        if detector_source:
            actor = OriginActor(type='tool', **{'actor-uuid': UUIDManager.actor_uuid(detector_source)})
            origin = Origin(actors=[actor], **{'related-tasks': None})
            origins = [origin]

        # Subjects are optional
        subjects = None
        asset_id = row_data.get(PoamXlsxHelper.ASSET_IDENTIFIER)
        if asset_id:
            subject = SubjectReference(**{'subject-uuid': UUIDManager.actor_uuid(asset_id)}, type='component')
            subjects = [subject]

        observation = Observation(
            uuid=UUIDManager.observation_uuid(poam_id),
            description=description,
            methods=methods,
            collected=collected,
            origins=origins,
            subjects=subjects,
            title=None,
            props=None,
            links=None,
            types=None,
            expires=None,
            **{'relevant-evidence': None},
        )

        return observation

    def create_risk(self, poam_id: str, row_data: Dict[str, Any], helper: PoamXlsxHelper) -> Risk:
        """
        Create Risk from row data.

        Args:
            poam_id: POAM ID
            row_data: Row data dictionary
            helper: PoamXlsxHelper instance

        Returns:
            Risk object
        """
        # Required fields - clean all text fields
        title = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_NAME, ''))
        description = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_DESCRIPTION, ''))
        statement_raw = row_data.get(PoamXlsxHelper.OVERALL_REMEDIATION_PLAN, description)
        # Convert to string and strip, handling both string and non-string values
        if statement_raw:
            statement = str(statement_raw).strip() if isinstance(statement_raw, str) else str(statement_raw)
        else:
            statement = description
        status = RiskStatus(__root__='open')  # Default status for Open POA&M Items sheet

        # Properties
        props = []

        # Helper function to clean and validate property values
        def add_property_if_valid(name: str, value: Any) -> None:
            """Add property if value is valid (non-empty after stripping)."""
            if value is None:
                return

            if isinstance(value, str):
                # Strip all whitespace including newlines, tabs, etc.
                cleaned = value.strip()
                # Additional check: ensure not just whitespace and matches OSCAL pattern
                if cleaned and not cleaned.isspace():
                    try:
                        props.append(
                            Property(name=name, value=cleaned, uuid=None, ns=None, **{'class': None}, group=None)
                        )
                    except Exception as e:
                        logger.warning(f'Could not create property {name} with value "{cleaned[:50]}...": {e}')
            elif value:
                # Non-string value, convert to string
                props.append(Property(name=name, value=str(value), uuid=None, ns=None, **{'class': None}, group=None))

        # Risk ratings as properties
        add_property_if_valid('original-risk-rating', row_data.get(PoamXlsxHelper.ORIGINAL_RISK_RATING))
        add_property_if_valid('adjusted-risk-rating', row_data.get(PoamXlsxHelper.ADJUSTED_RISK_RATING))
        add_property_if_valid('risk-adjustment', row_data.get(PoamXlsxHelper.RISK_ADJUSTMENT))
        add_property_if_valid('false-positive', row_data.get(PoamXlsxHelper.FALSE_POSITIVE))
        add_property_if_valid('operational-requirement', row_data.get(PoamXlsxHelper.OPERATIONAL_REQUIREMENT))
        add_property_if_valid('deviation-rationale', row_data.get(PoamXlsxHelper.DEVIATION_RATIONALE))

        # Deadline is optional
        deadline = None
        completion_date_value = row_data.get(PoamXlsxHelper.SCHEDULED_COMPLETION_DATE)
        if completion_date_value:
            deadline = helper.parse_date(completion_date_value)

        # Remediations with milestones (optional)
        remediations = None
        milestones_str = row_data.get(PoamXlsxHelper.PLANNED_MILESTONES)
        if milestones_str:
            milestones = helper.parse_milestones(milestones_str)
            if milestones:
                tasks = self._create_milestone_tasks(poam_id, milestones, helper)
                remediation = Response(
                    uuid=UUIDManager.remediation_uuid(poam_id),
                    lifecycle='planned',
                    title=f'Remediation for {poam_id}',
                    description=statement,
                    tasks=tasks or None,
                    props=None,
                    links=None,
                    origins=None,
                    **{'required-assets': None},
                )
                remediations = [remediation]

        risk = Risk(
            uuid=UUIDManager.risk_uuid(poam_id),
            title=title,
            description=description,
            statement=statement,
            status=status,
            props=props or None,
            deadline=deadline,
            remediations=remediations,
            links=None,
            origins=None,
            **{
                'threat-ids': None,
                'characterizations': None,
                'mitigating-factors': None,
                'risk-log': None,
                'related-observations': None,
            },
        )

        return risk

    def _create_milestone_tasks(
        self, poam_id: str, milestones: List[Dict[str, Any]], helper: PoamXlsxHelper
    ) -> List[OscalTask]:
        """
        Create OSCAL Task objects from milestone data.

        Args:
            poam_id: POAM ID
            milestones: List of milestone dictionaries
            helper: PoamXlsxHelper instance

        Returns:
            List of OscalTask objects
        """
        tasks = []

        for idx, milestone in enumerate(milestones):
            title = milestone.get('title', '')
            description = milestone.get('description')

            # Timing is optional
            timing = None
            date_str = milestone.get('timing')
            if date_str:
                try:
                    end_date = helper.parse_date(date_str)
                    if end_date:
                        # Create a date range (start = now, end = milestone date)
                        start_date = datetime.datetime.fromisoformat(self._timestamp)
                        timing = Timing(**{'within-date-range': WithinDateRange(start=start_date, end=end_date)})
                except Exception as e:
                    logger.warning(f'Could not parse milestone date "{date_str}": {e}')

            task = OscalTask(
                uuid=UUIDManager.task_uuid(poam_id, idx),
                type='milestone',
                title=title,
                description=description,
                timing=timing,
                props=None,
                links=None,
                dependencies=None,
                subjects=None,
                **{'associated-activities': None, 'responsible-roles': None},
            )
            tasks.append(task)

        return tasks

    def link_objects(self, poam_item: PoamItem, observation: Observation, risk: Risk) -> None:
        """
        Link POAM objects together via UUID references.

        Args:
            poam_item: PoamItem to link
            observation: Observation to link
            risk: Risk to link
        """
        # Link PoamItem to Observation
        poam_item.related_observations = [RelatedObservation(**{'observation-uuid': observation.uuid})]

        # Link PoamItem to Risk
        poam_item.related_risks = [AssociatedRisk(**{'risk-uuid': risk.uuid})]

        # Link Risk to Observation
        risk.related_observations = [RelatedObservation(**{'observation-uuid': observation.uuid})]
Methods:¤
__init__(timestamp, validator) ¤

Initialize builder.

Parameters:

Name Type Description Default
timestamp str

ISO timestamp for metadata

required
validator PoamValidator

PoamValidator instance

required
Source code in trestle/tasks/xlsx_to_oscal_poam.py
491
492
493
494
495
496
497
498
499
500
def __init__(self, timestamp: str, validator: PoamValidator) -> None:
    """
    Initialize builder.

    Args:
        timestamp: ISO timestamp for metadata
        validator: PoamValidator instance
    """
    self._timestamp = timestamp
    self._validator = validator
create_observation(poam_id, row_data, helper) ¤

Create Observation from row data.

Parameters:

Name Type Description Default
poam_id str

POAM ID

required
row_data Dict[str, Any]

Row data dictionary

required
helper PoamXlsxHelper

PoamXlsxHelper instance

required

Returns:

Type Description
Observation

Observation object

Source code in trestle/tasks/xlsx_to_oscal_poam.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def create_observation(self, poam_id: str, row_data: Dict[str, Any], helper: PoamXlsxHelper) -> Observation:
    """
    Create Observation from row data.

    Args:
        poam_id: POAM ID
        row_data: Row data dictionary
        helper: PoamXlsxHelper instance

    Returns:
        Observation object
    """
    weakness_name = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_NAME, ''))

    # Description is required
    description = f'Weakness detected: {weakness_name}'
    weakness_source_id = row_data.get(PoamXlsxHelper.WEAKNESS_SOURCE_IDENTIFIER)
    if weakness_source_id and isinstance(weakness_source_id, str):
        weakness_source_id = weakness_source_id.strip()
        if weakness_source_id:
            description += f' (Source: {weakness_source_id})'

    # Collected date (required)
    detection_date_value = row_data.get(PoamXlsxHelper.ORIGINAL_DETECTION_DATE)
    collected = helper.parse_date(detection_date_value)
    if collected is None:
        # Default to current timestamp if no date provided
        collected = datetime.datetime.fromisoformat(self._timestamp)

    # Methods are required
    methods = ['TEST']

    # Origins are optional
    origins = None
    detector_source = row_data.get(PoamXlsxHelper.WEAKNESS_DETECTOR_SOURCE)
    if detector_source:
        actor = OriginActor(type='tool', **{'actor-uuid': UUIDManager.actor_uuid(detector_source)})
        origin = Origin(actors=[actor], **{'related-tasks': None})
        origins = [origin]

    # Subjects are optional
    subjects = None
    asset_id = row_data.get(PoamXlsxHelper.ASSET_IDENTIFIER)
    if asset_id:
        subject = SubjectReference(**{'subject-uuid': UUIDManager.actor_uuid(asset_id)}, type='component')
        subjects = [subject]

    observation = Observation(
        uuid=UUIDManager.observation_uuid(poam_id),
        description=description,
        methods=methods,
        collected=collected,
        origins=origins,
        subjects=subjects,
        title=None,
        props=None,
        links=None,
        types=None,
        expires=None,
        **{'relevant-evidence': None},
    )

    return observation
create_poam_item(poam_id, row_data) ¤

Create PoamItem from row data.

Parameters:

Name Type Description Default
poam_id str

POAM ID

required
row_data Dict[str, Any]

Row data dictionary

required

Returns:

Type Description
PoamItem

PoamItem object

Source code in trestle/tasks/xlsx_to_oscal_poam.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def create_poam_item(self, poam_id: str, row_data: Dict[str, Any]) -> PoamItem:
    """
    Create PoamItem from row data.

    Args:
        poam_id: POAM ID
        row_data: Row data dictionary

    Returns:
        PoamItem object
    """
    # Required fields
    title = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_NAME, ''))
    description = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_DESCRIPTION, ''))

    # Optional fields
    comments = row_data.get(PoamXlsxHelper.COMMENTS)
    if comments and isinstance(comments, str):
        comments = comments.strip() or None

    # Build properties
    props = []

    # Add POAM ID as property (clean it first)
    clean_poam_id = _safe_strip(poam_id) if poam_id else poam_id
    if clean_poam_id:
        props.append(
            Property(name='poam-id', value=clean_poam_id, uuid=None, ns=None, **{'class': None}, group=None)
        )

    # Add control IDs as properties
    controls_str = row_data.get(PoamXlsxHelper.CONTROLS, '')
    if controls_str:
        controls = self._validator.parse_controls(controls_str)
        for ctrl_id in controls:
            props.append(
                Property(name='control-id', value=ctrl_id, uuid=None, ns=None, **{'class': None}, group=None)
            )

    # Create PoamItem
    poam_item = PoamItem(
        uuid=UUIDManager.poam_item_uuid(poam_id),
        title=title,
        description=description,
        props=props or None,
        links=None,
        origins=None,
        **{'related-findings': None, 'related-observations': None, 'related-risks': None},
    )

    # Add remarks if present
    if comments:
        poam_item.remarks = comments

    return poam_item
create_risk(poam_id, row_data, helper) ¤

Create Risk from row data.

Parameters:

Name Type Description Default
poam_id str

POAM ID

required
row_data Dict[str, Any]

Row data dictionary

required
helper PoamXlsxHelper

PoamXlsxHelper instance

required

Returns:

Type Description
Risk

Risk object

Source code in trestle/tasks/xlsx_to_oscal_poam.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def create_risk(self, poam_id: str, row_data: Dict[str, Any], helper: PoamXlsxHelper) -> Risk:
    """
    Create Risk from row data.

    Args:
        poam_id: POAM ID
        row_data: Row data dictionary
        helper: PoamXlsxHelper instance

    Returns:
        Risk object
    """
    # Required fields - clean all text fields
    title = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_NAME, ''))
    description = _safe_strip(row_data.get(PoamXlsxHelper.WEAKNESS_DESCRIPTION, ''))
    statement_raw = row_data.get(PoamXlsxHelper.OVERALL_REMEDIATION_PLAN, description)
    # Convert to string and strip, handling both string and non-string values
    if statement_raw:
        statement = str(statement_raw).strip() if isinstance(statement_raw, str) else str(statement_raw)
    else:
        statement = description
    status = RiskStatus(__root__='open')  # Default status for Open POA&M Items sheet

    # Properties
    props = []

    # Helper function to clean and validate property values
    def add_property_if_valid(name: str, value: Any) -> None:
        """Add property if value is valid (non-empty after stripping)."""
        if value is None:
            return

        if isinstance(value, str):
            # Strip all whitespace including newlines, tabs, etc.
            cleaned = value.strip()
            # Additional check: ensure not just whitespace and matches OSCAL pattern
            if cleaned and not cleaned.isspace():
                try:
                    props.append(
                        Property(name=name, value=cleaned, uuid=None, ns=None, **{'class': None}, group=None)
                    )
                except Exception as e:
                    logger.warning(f'Could not create property {name} with value "{cleaned[:50]}...": {e}')
        elif value:
            # Non-string value, convert to string
            props.append(Property(name=name, value=str(value), uuid=None, ns=None, **{'class': None}, group=None))

    # Risk ratings as properties
    add_property_if_valid('original-risk-rating', row_data.get(PoamXlsxHelper.ORIGINAL_RISK_RATING))
    add_property_if_valid('adjusted-risk-rating', row_data.get(PoamXlsxHelper.ADJUSTED_RISK_RATING))
    add_property_if_valid('risk-adjustment', row_data.get(PoamXlsxHelper.RISK_ADJUSTMENT))
    add_property_if_valid('false-positive', row_data.get(PoamXlsxHelper.FALSE_POSITIVE))
    add_property_if_valid('operational-requirement', row_data.get(PoamXlsxHelper.OPERATIONAL_REQUIREMENT))
    add_property_if_valid('deviation-rationale', row_data.get(PoamXlsxHelper.DEVIATION_RATIONALE))

    # Deadline is optional
    deadline = None
    completion_date_value = row_data.get(PoamXlsxHelper.SCHEDULED_COMPLETION_DATE)
    if completion_date_value:
        deadline = helper.parse_date(completion_date_value)

    # Remediations with milestones (optional)
    remediations = None
    milestones_str = row_data.get(PoamXlsxHelper.PLANNED_MILESTONES)
    if milestones_str:
        milestones = helper.parse_milestones(milestones_str)
        if milestones:
            tasks = self._create_milestone_tasks(poam_id, milestones, helper)
            remediation = Response(
                uuid=UUIDManager.remediation_uuid(poam_id),
                lifecycle='planned',
                title=f'Remediation for {poam_id}',
                description=statement,
                tasks=tasks or None,
                props=None,
                links=None,
                origins=None,
                **{'required-assets': None},
            )
            remediations = [remediation]

    risk = Risk(
        uuid=UUIDManager.risk_uuid(poam_id),
        title=title,
        description=description,
        statement=statement,
        status=status,
        props=props or None,
        deadline=deadline,
        remediations=remediations,
        links=None,
        origins=None,
        **{
            'threat-ids': None,
            'characterizations': None,
            'mitigating-factors': None,
            'risk-log': None,
            'related-observations': None,
        },
    )

    return risk

Link POAM objects together via UUID references.

Parameters:

Name Type Description Default
poam_item PoamItem

PoamItem to link

required
observation Observation

Observation to link

required
risk Risk

Risk to link

required
Source code in trestle/tasks/xlsx_to_oscal_poam.py
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def link_objects(self, poam_item: PoamItem, observation: Observation, risk: Risk) -> None:
    """
    Link POAM objects together via UUID references.

    Args:
        poam_item: PoamItem to link
        observation: Observation to link
        risk: Risk to link
    """
    # Link PoamItem to Observation
    poam_item.related_observations = [RelatedObservation(**{'observation-uuid': observation.uuid})]

    # Link PoamItem to Risk
    poam_item.related_risks = [AssociatedRisk(**{'risk-uuid': risk.uuid})]

    # Link Risk to Observation
    risk.related_observations = [RelatedObservation(**{'observation-uuid': observation.uuid})]

PoamValidator ¤

Validate POAM spreadsheet data before transformation.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
 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
class PoamValidator:
    """Validate POAM spreadsheet data before transformation."""

    VALID_RISK_RATINGS = ['Low', 'Moderate', 'High', 'N/A']
    VALID_YES_NO_PENDING = ['Yes', 'No', 'Pending']
    CONTROL_PATTERN = re.compile(r'^[A-Z]{2}-\d+(\(\d+\))?$')

    def __init__(self, validate_mode: str = 'warn') -> None:
        """
        Initialize validator.

        Args:
            validate_mode: 'on' (fail on error), 'warn' (log warnings), or 'off' (skip validation)
        """
        self.validate_mode = validate_mode
        self.errors: List[str] = []
        self.warnings: List[str] = []

    def validate_row(self, row_num: int, row_data: Dict[str, Any]) -> List[str]:
        """
        Validate a single row of data.

        Args:
            row_num: Row number in spreadsheet
            row_data: Dictionary of column_name -> value

        Returns:
            List of validation error messages
        """
        errors = []

        # Required fields
        if not row_data.get('POAM ID'):
            errors.append(f'Row {row_num}: Missing required field "POAM ID"')
        if not row_data.get('Weakness Name'):
            errors.append(f'Row {row_num}: Missing required field "Weakness Name"')
        if not row_data.get('Weakness Description'):
            errors.append(f'Row {row_num}: Missing required field "Weakness Description"')
        if not row_data.get('Controls'):
            errors.append(f'Row {row_num}: Missing required field "Controls"')

        # Risk rating validation
        for rating_field in ['Original Risk Rating', 'Adjusted Risk Rating']:
            value = row_data.get(rating_field, '')
            if value and value not in self.VALID_RISK_RATINGS:
                errors.append(
                    f'Row {row_num}: Invalid {rating_field}: "{value}". '
                    f'Must be one of: {", ".join(self.VALID_RISK_RATINGS)}'
                )

        # Yes/No/Pending field validation
        for field in ['Risk Adjustment', 'False Positive', 'Operational Requirement']:
            value = row_data.get(field, '')
            if value and value not in self.VALID_YES_NO_PENDING:
                errors.append(
                    f'Row {row_num}: Invalid {field}: "{value}". '
                    f'Must be one of: {", ".join(self.VALID_YES_NO_PENDING[:-1])}'
                )

        self.errors.extend(errors)
        return errors

    def parse_controls(self, controls_str: str) -> List[str]:
        """
        Parse and validate control IDs.

        Args:
            controls_str: Comma/space-separated control IDs like "AC-1, AC-2, SC-7(5)"

        Returns:
            List of validated control IDs
        """
        if not controls_str:
            return []

        # Split by comma and/or space
        controls = re.split(r'[,\s]+', controls_str.strip())

        validated = []
        for ctrl in controls:
            ctrl = ctrl.strip()
            if not ctrl:
                continue
            if self.CONTROL_PATTERN.match(ctrl.upper()):
                validated.append(ctrl.upper())
            else:
                if self.validate_mode != 'off':
                    logger.warning(f'Invalid control format: "{ctrl}" (expected format: XX-N or XX-N(N))')

        return validated

    def log_validation_results(self) -> bool:
        """
        Log validation results based on validation mode.

        Returns:
            True if validation passed or mode is 'warn'/'off', False if errors in 'on' mode
        """
        if self.validate_mode == 'off':
            return True

        if self.errors:
            if self.validate_mode == 'on':
                for error in self.errors:
                    logger.error(error)
                return False
            else:  # warn mode
                for error in self.errors:
                    logger.warning(error)

        if self.warnings:
            for warning in self.warnings:
                logger.warning(warning)

        return True
Attributes¤
CONTROL_PATTERN = re.compile('^[A-Z]{2}-\\d+(\\(\\d+\\))?$') class-attribute instance-attribute ¤
VALID_RISK_RATINGS = ['Low', 'Moderate', 'High', 'N/A'] class-attribute instance-attribute ¤
VALID_YES_NO_PENDING = ['Yes', 'No', 'Pending'] class-attribute instance-attribute ¤
errors = [] instance-attribute ¤
validate_mode = validate_mode instance-attribute ¤
warnings = [] instance-attribute ¤
Methods:¤
__init__(validate_mode='warn') ¤

Initialize validator.

Parameters:

Name Type Description Default
validate_mode str

'on' (fail on error), 'warn' (log warnings), or 'off' (skip validation)

'warn'
Source code in trestle/tasks/xlsx_to_oscal_poam.py
102
103
104
105
106
107
108
109
110
111
def __init__(self, validate_mode: str = 'warn') -> None:
    """
    Initialize validator.

    Args:
        validate_mode: 'on' (fail on error), 'warn' (log warnings), or 'off' (skip validation)
    """
    self.validate_mode = validate_mode
    self.errors: List[str] = []
    self.warnings: List[str] = []
log_validation_results() ¤

Log validation results based on validation mode.

Returns:

Type Description
bool

True if validation passed or mode is 'warn'/'off', False if errors in 'on' mode

Source code in trestle/tasks/xlsx_to_oscal_poam.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def log_validation_results(self) -> bool:
    """
    Log validation results based on validation mode.

    Returns:
        True if validation passed or mode is 'warn'/'off', False if errors in 'on' mode
    """
    if self.validate_mode == 'off':
        return True

    if self.errors:
        if self.validate_mode == 'on':
            for error in self.errors:
                logger.error(error)
            return False
        else:  # warn mode
            for error in self.errors:
                logger.warning(error)

    if self.warnings:
        for warning in self.warnings:
            logger.warning(warning)

    return True
parse_controls(controls_str) ¤

Parse and validate control IDs.

Parameters:

Name Type Description Default
controls_str str

Comma/space-separated control IDs like "AC-1, AC-2, SC-7(5)"

required

Returns:

Type Description
List[str]

List of validated control IDs

Source code in trestle/tasks/xlsx_to_oscal_poam.py
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
def parse_controls(self, controls_str: str) -> List[str]:
    """
    Parse and validate control IDs.

    Args:
        controls_str: Comma/space-separated control IDs like "AC-1, AC-2, SC-7(5)"

    Returns:
        List of validated control IDs
    """
    if not controls_str:
        return []

    # Split by comma and/or space
    controls = re.split(r'[,\s]+', controls_str.strip())

    validated = []
    for ctrl in controls:
        ctrl = ctrl.strip()
        if not ctrl:
            continue
        if self.CONTROL_PATTERN.match(ctrl.upper()):
            validated.append(ctrl.upper())
        else:
            if self.validate_mode != 'off':
                logger.warning(f'Invalid control format: "{ctrl}" (expected format: XX-N or XX-N(N))')

    return validated
validate_row(row_num, row_data) ¤

Validate a single row of data.

Parameters:

Name Type Description Default
row_num int

Row number in spreadsheet

required
row_data Dict[str, Any]

Dictionary of column_name -> value

required

Returns:

Type Description
List[str]

List of validation error messages

Source code in trestle/tasks/xlsx_to_oscal_poam.py
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
def validate_row(self, row_num: int, row_data: Dict[str, Any]) -> List[str]:
    """
    Validate a single row of data.

    Args:
        row_num: Row number in spreadsheet
        row_data: Dictionary of column_name -> value

    Returns:
        List of validation error messages
    """
    errors = []

    # Required fields
    if not row_data.get('POAM ID'):
        errors.append(f'Row {row_num}: Missing required field "POAM ID"')
    if not row_data.get('Weakness Name'):
        errors.append(f'Row {row_num}: Missing required field "Weakness Name"')
    if not row_data.get('Weakness Description'):
        errors.append(f'Row {row_num}: Missing required field "Weakness Description"')
    if not row_data.get('Controls'):
        errors.append(f'Row {row_num}: Missing required field "Controls"')

    # Risk rating validation
    for rating_field in ['Original Risk Rating', 'Adjusted Risk Rating']:
        value = row_data.get(rating_field, '')
        if value and value not in self.VALID_RISK_RATINGS:
            errors.append(
                f'Row {row_num}: Invalid {rating_field}: "{value}". '
                f'Must be one of: {", ".join(self.VALID_RISK_RATINGS)}'
            )

    # Yes/No/Pending field validation
    for field in ['Risk Adjustment', 'False Positive', 'Operational Requirement']:
        value = row_data.get(field, '')
        if value and value not in self.VALID_YES_NO_PENDING:
            errors.append(
                f'Row {row_num}: Invalid {field}: "{value}". '
                f'Must be one of: {", ".join(self.VALID_YES_NO_PENDING[:-1])}'
            )

    self.errors.extend(errors)
    return errors

PoamXlsxHelper ¤

Helper class for reading POAM spreadsheet templates.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
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
class PoamXlsxHelper:
    """Helper class for reading POAM spreadsheet templates."""

    # Column name constants
    POAM_ID = 'POAM ID'
    CONTROLS = 'Controls'
    WEAKNESS_NAME = 'Weakness Name'
    WEAKNESS_DESCRIPTION = 'Weakness Description'
    WEAKNESS_DETECTOR_SOURCE = 'Weakness Detector Source'
    WEAKNESS_SOURCE_IDENTIFIER = 'Weakness Source Identifier'
    ASSET_IDENTIFIER = 'Asset Identifier'
    POINT_OF_CONTACT = 'Point of Contact'
    RESOURCES_REQUIRED = 'Resources Required'
    OVERALL_REMEDIATION_PLAN = 'Overall Remediation Plan'
    ORIGINAL_DETECTION_DATE = 'Original Detection Date'
    SCHEDULED_COMPLETION_DATE = 'Scheduled Completion Date'
    PLANNED_MILESTONES = 'Planned Milestones'
    MILESTONE_CHANGES = 'Milestone Changes'
    STATUS_DATE = 'Status Date'
    VENDOR_DEPENDENCY = 'Vendor Dependency'
    LAST_VENDOR_CHECKIN_DATE = 'Last Vendor Check-in Date'
    VENDOR_DEPENDENT_PRODUCT_NAME = 'Vendor Dependent Product Name'
    ORIGINAL_RISK_RATING = 'Original Risk Rating'
    ADJUSTED_RISK_RATING = 'Adjusted Risk Rating'
    RISK_ADJUSTMENT = 'Risk Adjustment'
    FALSE_POSITIVE = 'False Positive'
    OPERATIONAL_REQUIREMENT = 'Operational Requirement'
    DEVIATION_RATIONALE = 'Deviation Rationale'
    SUPPORTING_DOCUMENTS = 'Supporting Documents'
    COMMENTS = 'Comments'
    AUTO_APPROVE = 'Auto-Approve'
    BOD_22_01_TRACKING = 'Binding Operational Directive 22-01 tracking'
    BOD_22_01_DUE_DATE = 'Binding Operational Directive 22-01 Due Date'
    CVE = 'CVE'
    SERVICE_NAME = 'Service Name'

    def __init__(self) -> None:
        """Initialize helper."""
        self._column_map: Dict[str, int] = {}
        self._work_sheet = None
        self._header_row = 5  # Template has headers at row 5 (1-indexed)

    def load(self, xlsx_path: pathlib.Path, sheet_name: str = 'Open POA&M Items') -> None:
        """
        Load spreadsheet file and map columns.

        Args:
            xlsx_path: Path to spreadsheet file
            sheet_name: Name of worksheet to load

        Raises:
            FileNotFoundError: If file doesn't exist
            KeyError: If worksheet doesn't exist
        """
        if not xlsx_path.exists():
            raise FileNotFoundError(f'Spreadsheet file not found: {xlsx_path}')

        workbook = load_workbook(filename=str(xlsx_path), data_only=True)

        if sheet_name not in workbook.sheetnames:
            available = ', '.join(workbook.sheetnames)
            raise KeyError(f'Worksheet "{sheet_name}" not found. Available sheets: {available}')

        self._work_sheet = workbook[sheet_name]
        self._map_columns()

    def _map_columns(self) -> None:
        """Map column names to column indices from header row."""
        if self._work_sheet is None:
            return

        # Read header row (row 5 in template, 1-indexed)
        for cell in self._work_sheet[self._header_row]:
            if cell.value and isinstance(cell.value, str):
                col_name = cell.value.strip()
                if col_name:
                    self._column_map[col_name] = cell.column

        logger.debug(f'Mapped {len(self._column_map)} columns')
        if not self._column_map:
            logger.warning(
                f'No columns mapped from row {self._header_row}. '
                'Verify the spreadsheet uses the expected FedRAMP POAM template format.'
            )

    def row_generator(self) -> Iterator[Tuple[int, Dict[str, Any]]]:
        """
        Generate row numbers and data dictionaries for data rows.

        Yields:
            Tuple of (row_number, row_data_dict)
        """
        if self._work_sheet is None:
            return

        # Data starts at row 6 (after header at row 5)
        data_start_row = self._header_row + 1
        max_row = self._work_sheet.max_row

        for row_num in range(data_start_row, max_row + 1):
            row_data = self._get_row_data(row_num)

            # Skip empty rows (no POAM ID)
            if not row_data.get(self.POAM_ID):
                continue

            yield row_num, row_data

    def _get_row_data(self, row_num: int) -> Dict[str, Any]:
        """
        Extract data from a row as dictionary.

        Args:
            row_num: Row number (1-indexed)

        Returns:
            Dictionary mapping column names to cell values
        """
        row_data = {}

        for col_name, col_idx in self._column_map.items():
            cell = self._work_sheet.cell(row=row_num, column=col_idx)
            value = None if isinstance(cell, MergedCell) else cell.value
            row_data[col_name] = self._clean_value(value)

        return row_data

    def _clean_value(self, value: Any) -> Any:
        """
        Clean cell value.

        Args:
            value: Raw cell value

        Returns:
            Cleaned value (strings are stripped, None for empty)
        """
        if value is None:
            return None
        if isinstance(value, str):
            value = value.strip()
            return value if value else None
        return value

    def parse_date(self, date_value: Any) -> Optional[datetime.datetime]:
        """
        Parse spreadsheet date to datetime with timezone.

        Args:
            date_value: Spreadsheet date (datetime object or string)

        Returns:
            datetime with UTC timezone or None
        """
        if date_value is None:
            return None

        if isinstance(date_value, datetime.datetime):
            # Add timezone if missing
            if date_value.tzinfo is None:
                return date_value.replace(tzinfo=datetime.timezone.utc)
            return date_value

        if isinstance(date_value, datetime.date):
            # Convert date to datetime
            dt = datetime.datetime.combine(date_value, datetime.time.min)
            return dt.replace(tzinfo=datetime.timezone.utc)

        if isinstance(date_value, str):
            # Try to parse ISO 8601 format
            try:
                dt = datetime.datetime.fromisoformat(date_value.replace('Z', '+00:00'))
                if dt.tzinfo is None:
                    dt = dt.replace(tzinfo=datetime.timezone.utc)
                return dt
            except (ValueError, AttributeError):
                logger.warning(f'Could not parse date string: "{date_value}"')
                return None

        logger.warning(f'Unexpected date type: {type(date_value)}')
        return None

    def parse_milestones(self, milestones_str: str) -> List[Dict[str, Any]]:
        """
        Parse milestone text into structured format.

        Args:
            milestones_str: Milestone text (may contain multiple milestones)

        Returns:
            List of milestone dictionaries with 'title', 'description', optional 'timing'
        """
        if not milestones_str:
            return []

        milestones = []
        lines = milestones_str.split('\n')

        for line in lines:
            line = line.strip()
            if not line:
                continue

            # Try to parse: "Milestone N: Description [by YYYY-MM-DD]"
            # Use a safer approach: first extract the date if present, then parse the rest
            # This avoids catastrophic backtracking from the original pattern
            date_str = None
            main_line = line

            # Check if line ends with a date pattern and extract it
            # Use string methods instead of regex to avoid ReDoS vulnerability
            # Look for " by YYYY-MM-DD" at the end of the line (14 chars: " by 2024-01-15")
            if len(line) >= 14:
                # Check last 14 chars for " by YYYY-MM-DD" pattern (case-insensitive)
                potential_date_part = line[-14:]
                # Check structure: " by " (4 chars) + "YYYY-MM-DD" (10 chars)
                # Indices in potential_date_part: 0-3=" by ", 4-7=YYYY, 8=-, 9-10=MM, 11=-, 12-13=DD
                if (
                    potential_date_part[:4].lower() == ' by '
                    and len(potential_date_part) == 14
                    and potential_date_part[8] == '-'
                    and potential_date_part[11] == '-'
                ):
                    # Validate it's actually a date format
                    year = potential_date_part[4:8]
                    month = potential_date_part[9:11]
                    day = potential_date_part[12:14]
                    if year.isdigit() and month.isdigit() and day.isdigit():
                        date_str = f'{year}-{month}-{day}'
                        main_line = line[:-14].rstrip()

            # Parse milestone prefix using string operations to avoid any regex ReDoS risk
            # This approach is deterministic and has O(n) complexity with no backtracking
            main_line_lower = main_line.lower()
            milestone_num = None
            remainder = ''

            # Check for "Milestone N" or "Milestone N:" or "Milestone N." patterns
            if main_line_lower.startswith('milestone '):
                # Find the end of "Milestone" and skip whitespace
                idx = 9  # len('milestone')
                while idx < len(main_line) and main_line[idx].isspace():
                    idx += 1
                # Now find the end of the number
                num_start = idx
                while idx < len(main_line) and main_line[idx].isdigit():
                    idx += 1
                if idx > num_start:  # Found at least one digit
                    milestone_num = main_line[:idx]
                    remainder = main_line[idx:]
            # Check for "MN" or "MN:" or "MN." patterns
            elif len(main_line) > 1 and main_line_lower[0] == 'm' and main_line[1].isdigit():
                idx = 1
                while idx < len(main_line) and main_line[idx].isdigit():
                    idx += 1
                milestone_num = main_line[:idx]
                remainder = main_line[idx:]

            if milestone_num:
                # Strip optional separator and whitespace from remainder
                description = remainder.lstrip(':. ')
                # If no description after prefix, use the entire line as title
                if description:
                    milestone = {'title': description, 'description': milestone_num.strip()}
                else:
                    milestone = {'title': main_line.strip(), 'description': 'Milestone'}
                if date_str:
                    milestone['timing'] = date_str
                milestones.append(milestone)
            else:
                # Fallback: treat entire line as milestone title
                milestones.append({'title': line, 'description': 'Milestone'})

        return milestones
Attributes¤
ADJUSTED_RISK_RATING = 'Adjusted Risk Rating' class-attribute instance-attribute ¤
ASSET_IDENTIFIER = 'Asset Identifier' class-attribute instance-attribute ¤
AUTO_APPROVE = 'Auto-Approve' class-attribute instance-attribute ¤
BOD_22_01_DUE_DATE = 'Binding Operational Directive 22-01 Due Date' class-attribute instance-attribute ¤
BOD_22_01_TRACKING = 'Binding Operational Directive 22-01 tracking' class-attribute instance-attribute ¤
COMMENTS = 'Comments' class-attribute instance-attribute ¤
CONTROLS = 'Controls' class-attribute instance-attribute ¤
CVE = 'CVE' class-attribute instance-attribute ¤
DEVIATION_RATIONALE = 'Deviation Rationale' class-attribute instance-attribute ¤
FALSE_POSITIVE = 'False Positive' class-attribute instance-attribute ¤
LAST_VENDOR_CHECKIN_DATE = 'Last Vendor Check-in Date' class-attribute instance-attribute ¤
MILESTONE_CHANGES = 'Milestone Changes' class-attribute instance-attribute ¤
OPERATIONAL_REQUIREMENT = 'Operational Requirement' class-attribute instance-attribute ¤
ORIGINAL_DETECTION_DATE = 'Original Detection Date' class-attribute instance-attribute ¤
ORIGINAL_RISK_RATING = 'Original Risk Rating' class-attribute instance-attribute ¤
OVERALL_REMEDIATION_PLAN = 'Overall Remediation Plan' class-attribute instance-attribute ¤
PLANNED_MILESTONES = 'Planned Milestones' class-attribute instance-attribute ¤
POAM_ID = 'POAM ID' class-attribute instance-attribute ¤
POINT_OF_CONTACT = 'Point of Contact' class-attribute instance-attribute ¤
RESOURCES_REQUIRED = 'Resources Required' class-attribute instance-attribute ¤
RISK_ADJUSTMENT = 'Risk Adjustment' class-attribute instance-attribute ¤
SCHEDULED_COMPLETION_DATE = 'Scheduled Completion Date' class-attribute instance-attribute ¤
SERVICE_NAME = 'Service Name' class-attribute instance-attribute ¤
STATUS_DATE = 'Status Date' class-attribute instance-attribute ¤
SUPPORTING_DOCUMENTS = 'Supporting Documents' class-attribute instance-attribute ¤
VENDOR_DEPENDENCY = 'Vendor Dependency' class-attribute instance-attribute ¤
VENDOR_DEPENDENT_PRODUCT_NAME = 'Vendor Dependent Product Name' class-attribute instance-attribute ¤
WEAKNESS_DESCRIPTION = 'Weakness Description' class-attribute instance-attribute ¤
WEAKNESS_DETECTOR_SOURCE = 'Weakness Detector Source' class-attribute instance-attribute ¤
WEAKNESS_NAME = 'Weakness Name' class-attribute instance-attribute ¤
WEAKNESS_SOURCE_IDENTIFIER = 'Weakness Source Identifier' class-attribute instance-attribute ¤
Methods:¤
__init__() ¤

Initialize helper.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
248
249
250
251
252
def __init__(self) -> None:
    """Initialize helper."""
    self._column_map: Dict[str, int] = {}
    self._work_sheet = None
    self._header_row = 5  # Template has headers at row 5 (1-indexed)
load(xlsx_path, sheet_name='Open POA&M Items') ¤

Load spreadsheet file and map columns.

Parameters:

Name Type Description Default
xlsx_path Path

Path to spreadsheet file

required
sheet_name str

Name of worksheet to load

'Open POA&M Items'

Raises:

Type Description
FileNotFoundError

If file doesn't exist

KeyError

If worksheet doesn't exist

Source code in trestle/tasks/xlsx_to_oscal_poam.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def load(self, xlsx_path: pathlib.Path, sheet_name: str = 'Open POA&M Items') -> None:
    """
    Load spreadsheet file and map columns.

    Args:
        xlsx_path: Path to spreadsheet file
        sheet_name: Name of worksheet to load

    Raises:
        FileNotFoundError: If file doesn't exist
        KeyError: If worksheet doesn't exist
    """
    if not xlsx_path.exists():
        raise FileNotFoundError(f'Spreadsheet file not found: {xlsx_path}')

    workbook = load_workbook(filename=str(xlsx_path), data_only=True)

    if sheet_name not in workbook.sheetnames:
        available = ', '.join(workbook.sheetnames)
        raise KeyError(f'Worksheet "{sheet_name}" not found. Available sheets: {available}')

    self._work_sheet = workbook[sheet_name]
    self._map_columns()
parse_date(date_value) ¤

Parse spreadsheet date to datetime with timezone.

Parameters:

Name Type Description Default
date_value Any

Spreadsheet date (datetime object or string)

required

Returns:

Type Description
Optional[datetime]

datetime with UTC timezone or None

Source code in trestle/tasks/xlsx_to_oscal_poam.py
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
def parse_date(self, date_value: Any) -> Optional[datetime.datetime]:
    """
    Parse spreadsheet date to datetime with timezone.

    Args:
        date_value: Spreadsheet date (datetime object or string)

    Returns:
        datetime with UTC timezone or None
    """
    if date_value is None:
        return None

    if isinstance(date_value, datetime.datetime):
        # Add timezone if missing
        if date_value.tzinfo is None:
            return date_value.replace(tzinfo=datetime.timezone.utc)
        return date_value

    if isinstance(date_value, datetime.date):
        # Convert date to datetime
        dt = datetime.datetime.combine(date_value, datetime.time.min)
        return dt.replace(tzinfo=datetime.timezone.utc)

    if isinstance(date_value, str):
        # Try to parse ISO 8601 format
        try:
            dt = datetime.datetime.fromisoformat(date_value.replace('Z', '+00:00'))
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=datetime.timezone.utc)
            return dt
        except (ValueError, AttributeError):
            logger.warning(f'Could not parse date string: "{date_value}"')
            return None

    logger.warning(f'Unexpected date type: {type(date_value)}')
    return None
parse_milestones(milestones_str) ¤

Parse milestone text into structured format.

Parameters:

Name Type Description Default
milestones_str str

Milestone text (may contain multiple milestones)

required

Returns:

Type Description
List[Dict[str, Any]]

List of milestone dictionaries with 'title', 'description', optional 'timing'

Source code in trestle/tasks/xlsx_to_oscal_poam.py
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
def parse_milestones(self, milestones_str: str) -> List[Dict[str, Any]]:
    """
    Parse milestone text into structured format.

    Args:
        milestones_str: Milestone text (may contain multiple milestones)

    Returns:
        List of milestone dictionaries with 'title', 'description', optional 'timing'
    """
    if not milestones_str:
        return []

    milestones = []
    lines = milestones_str.split('\n')

    for line in lines:
        line = line.strip()
        if not line:
            continue

        # Try to parse: "Milestone N: Description [by YYYY-MM-DD]"
        # Use a safer approach: first extract the date if present, then parse the rest
        # This avoids catastrophic backtracking from the original pattern
        date_str = None
        main_line = line

        # Check if line ends with a date pattern and extract it
        # Use string methods instead of regex to avoid ReDoS vulnerability
        # Look for " by YYYY-MM-DD" at the end of the line (14 chars: " by 2024-01-15")
        if len(line) >= 14:
            # Check last 14 chars for " by YYYY-MM-DD" pattern (case-insensitive)
            potential_date_part = line[-14:]
            # Check structure: " by " (4 chars) + "YYYY-MM-DD" (10 chars)
            # Indices in potential_date_part: 0-3=" by ", 4-7=YYYY, 8=-, 9-10=MM, 11=-, 12-13=DD
            if (
                potential_date_part[:4].lower() == ' by '
                and len(potential_date_part) == 14
                and potential_date_part[8] == '-'
                and potential_date_part[11] == '-'
            ):
                # Validate it's actually a date format
                year = potential_date_part[4:8]
                month = potential_date_part[9:11]
                day = potential_date_part[12:14]
                if year.isdigit() and month.isdigit() and day.isdigit():
                    date_str = f'{year}-{month}-{day}'
                    main_line = line[:-14].rstrip()

        # Parse milestone prefix using string operations to avoid any regex ReDoS risk
        # This approach is deterministic and has O(n) complexity with no backtracking
        main_line_lower = main_line.lower()
        milestone_num = None
        remainder = ''

        # Check for "Milestone N" or "Milestone N:" or "Milestone N." patterns
        if main_line_lower.startswith('milestone '):
            # Find the end of "Milestone" and skip whitespace
            idx = 9  # len('milestone')
            while idx < len(main_line) and main_line[idx].isspace():
                idx += 1
            # Now find the end of the number
            num_start = idx
            while idx < len(main_line) and main_line[idx].isdigit():
                idx += 1
            if idx > num_start:  # Found at least one digit
                milestone_num = main_line[:idx]
                remainder = main_line[idx:]
        # Check for "MN" or "MN:" or "MN." patterns
        elif len(main_line) > 1 and main_line_lower[0] == 'm' and main_line[1].isdigit():
            idx = 1
            while idx < len(main_line) and main_line[idx].isdigit():
                idx += 1
            milestone_num = main_line[:idx]
            remainder = main_line[idx:]

        if milestone_num:
            # Strip optional separator and whitespace from remainder
            description = remainder.lstrip(':. ')
            # If no description after prefix, use the entire line as title
            if description:
                milestone = {'title': description, 'description': milestone_num.strip()}
            else:
                milestone = {'title': main_line.strip(), 'description': 'Milestone'}
            if date_str:
                milestone['timing'] = date_str
            milestones.append(milestone)
        else:
            # Fallback: treat entire line as milestone title
            milestones.append({'title': line, 'description': 'Milestone'})

    return milestones
row_generator() ¤

Generate row numbers and data dictionaries for data rows.

Yields:

Type Description
Tuple[int, Dict[str, Any]]

Tuple of (row_number, row_data_dict)

Source code in trestle/tasks/xlsx_to_oscal_poam.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def row_generator(self) -> Iterator[Tuple[int, Dict[str, Any]]]:
    """
    Generate row numbers and data dictionaries for data rows.

    Yields:
        Tuple of (row_number, row_data_dict)
    """
    if self._work_sheet is None:
        return

    # Data starts at row 6 (after header at row 5)
    data_start_row = self._header_row + 1
    max_row = self._work_sheet.max_row

    for row_num in range(data_start_row, max_row + 1):
        row_data = self._get_row_data(row_num)

        # Skip empty rows (no POAM ID)
        if not row_data.get(self.POAM_ID):
            continue

        yield row_num, row_data

UUIDManager ¤

Manage deterministic UUID generation for POAM objects.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
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
class UUIDManager:
    """Manage deterministic UUID generation for POAM objects."""

    # Namespace UUID for this task
    NAMESPACE = uuid.UUID('e8d8efc6-c23e-4e3e-a2e8-bc8fc08ff6c3')

    @staticmethod
    def poam_item_uuid(poam_id: str) -> str:
        """Generate deterministic UUID for PoamItem from POAM ID."""
        return str(uuid.uuid5(UUIDManager.NAMESPACE, f'poam-item-{poam_id}'))

    @staticmethod
    def observation_uuid(poam_id: str) -> str:
        """Generate deterministic UUID for Observation from POAM ID."""
        return str(uuid.uuid5(UUIDManager.NAMESPACE, f'observation-{poam_id}'))

    @staticmethod
    def risk_uuid(poam_id: str) -> str:
        """Generate deterministic UUID for Risk from POAM ID."""
        return str(uuid.uuid5(UUIDManager.NAMESPACE, f'risk-{poam_id}'))

    @staticmethod
    def task_uuid(poam_id: str, milestone_index: int) -> str:
        """Generate deterministic UUID for Task (milestone) from POAM ID + index."""
        return str(uuid.uuid5(UUIDManager.NAMESPACE, f'task-{poam_id}-{milestone_index}'))

    @staticmethod
    def actor_uuid(actor_name: str) -> str:
        """Generate deterministic UUID for Origin Actor."""
        return str(uuid.uuid5(UUIDManager.NAMESPACE, f'actor-{actor_name}'))

    @staticmethod
    def remediation_uuid(poam_id: str) -> str:
        """Generate deterministic UUID for Response (remediation) from POAM ID."""
        return str(uuid.uuid5(UUIDManager.NAMESPACE, f'remediation-{poam_id}'))
Attributes¤
NAMESPACE = uuid.UUID('e8d8efc6-c23e-4e3e-a2e8-bc8fc08ff6c3') class-attribute instance-attribute ¤
Methods:¤
actor_uuid(actor_name) staticmethod ¤

Generate deterministic UUID for Origin Actor.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
84
85
86
87
@staticmethod
def actor_uuid(actor_name: str) -> str:
    """Generate deterministic UUID for Origin Actor."""
    return str(uuid.uuid5(UUIDManager.NAMESPACE, f'actor-{actor_name}'))
observation_uuid(poam_id) staticmethod ¤

Generate deterministic UUID for Observation from POAM ID.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
69
70
71
72
@staticmethod
def observation_uuid(poam_id: str) -> str:
    """Generate deterministic UUID for Observation from POAM ID."""
    return str(uuid.uuid5(UUIDManager.NAMESPACE, f'observation-{poam_id}'))
poam_item_uuid(poam_id) staticmethod ¤

Generate deterministic UUID for PoamItem from POAM ID.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
64
65
66
67
@staticmethod
def poam_item_uuid(poam_id: str) -> str:
    """Generate deterministic UUID for PoamItem from POAM ID."""
    return str(uuid.uuid5(UUIDManager.NAMESPACE, f'poam-item-{poam_id}'))
remediation_uuid(poam_id) staticmethod ¤

Generate deterministic UUID for Response (remediation) from POAM ID.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
89
90
91
92
@staticmethod
def remediation_uuid(poam_id: str) -> str:
    """Generate deterministic UUID for Response (remediation) from POAM ID."""
    return str(uuid.uuid5(UUIDManager.NAMESPACE, f'remediation-{poam_id}'))
risk_uuid(poam_id) staticmethod ¤

Generate deterministic UUID for Risk from POAM ID.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
74
75
76
77
@staticmethod
def risk_uuid(poam_id: str) -> str:
    """Generate deterministic UUID for Risk from POAM ID."""
    return str(uuid.uuid5(UUIDManager.NAMESPACE, f'risk-{poam_id}'))
task_uuid(poam_id, milestone_index) staticmethod ¤

Generate deterministic UUID for Task (milestone) from POAM ID + index.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
79
80
81
82
@staticmethod
def task_uuid(poam_id: str, milestone_index: int) -> str:
    """Generate deterministic UUID for Task (milestone) from POAM ID + index."""
    return str(uuid.uuid5(UUIDManager.NAMESPACE, f'task-{poam_id}-{milestone_index}'))

XlsxToOscalPoam ¤

Bases: TaskBase


              flowchart TD
              trestle.tasks.xlsx_to_oscal_poam.XlsxToOscalPoam[XlsxToOscalPoam]
              trestle.tasks.base_task.TaskBase[TaskBase]

                              trestle.tasks.base_task.TaskBase --> trestle.tasks.xlsx_to_oscal_poam.XlsxToOscalPoam
                


              click trestle.tasks.xlsx_to_oscal_poam.XlsxToOscalPoam href "" "trestle.tasks.xlsx_to_oscal_poam.XlsxToOscalPoam"
              click trestle.tasks.base_task.TaskBase href "" "trestle.tasks.base_task.TaskBase"
            

Transform POAM spreadsheet to OSCAL POAM JSON.

This task reads a POAM spreadsheet template (specifically the "Open POA&M Items" worksheet) and transforms each row into an OSCAL Plan of Action and Milestones (POAM) JSON file.

Each spreadsheet row creates three linked OSCAL objects: 1. PoamItem: The main weakness/issue description 2. Observation: Details about when/how the weakness was detected 3. Risk: Risk assessment, remediation plan, and milestones

Configuration Example

[task.xlsx-to-oscal-poam] xlsx-file = POAM-Template.xlsx output-dir = output/ title = MySystem POA&M version = 1.0

Spreadsheet Requirements
  • Must use POAM template structure
  • Headers at row 5
  • Data starts at row 6
  • Required columns: POAM ID, Weakness Name, Weakness Description, Controls
See Also
  • docs/tutorials/task.xlsx-to-oscal-poam.md
  • OSCAL POAM specification
Source code in trestle/tasks/xlsx_to_oscal_poam.py
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
class XlsxToOscalPoam(TaskBase):
    """
    Transform POAM spreadsheet to OSCAL POAM JSON.

    This task reads a POAM spreadsheet template (specifically the
    "Open POA&M Items" worksheet) and transforms each row into an
    OSCAL Plan of Action and Milestones (POAM) JSON file.

    Each spreadsheet row creates three linked OSCAL objects:
    1. PoamItem: The main weakness/issue description
    2. Observation: Details about when/how the weakness was detected
    3. Risk: Risk assessment, remediation plan, and milestones

    Configuration Example:
        [task.xlsx-to-oscal-poam]
        xlsx-file = POAM-Template.xlsx
        output-dir = output/
        title = MySystem POA&M
        version = 1.0

    Spreadsheet Requirements:
        - Must use POAM template structure
        - Headers at row 5
        - Data starts at row 6
        - Required columns: POAM ID, Weakness Name, Weakness Description, Controls

    See Also:
        - docs/tutorials/task.xlsx-to-oscal-poam.md
        - OSCAL POAM specification
    """

    name = 'xlsx-to-oscal-poam'

    def __init__(self, config_object: Optional[configparser.SectionProxy]) -> None:
        """
        Initialize trestle task xlsx-to-oscal-poam.

        Args:
            config_object: Config section associated with the task.
        """
        super().__init__(config_object)
        self._timestamp = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat()

    def set_timestamp(self, timestamp: str) -> None:
        """Set the timestamp."""
        self._timestamp = timestamp

    def print_info(self) -> None:
        """Print the help string."""
        logger.info(f'Help information for {self.name} task.')
        logger.info('')
        logger.info('Purpose: Transform POAM spreadsheet to OSCAL POAM JSON format.')
        logger.info('')
        logger.info(f'Configuration flags sit under [task.{self.name}]:')
        text1 = '  xlsx-file                = '
        text2 = '(required) the path of the POAM spreadsheet file.'
        logger.info(text1 + text2)
        text1 = '  work-sheet-name          = '
        text2 = '(optional) the name of the work sheet in the spreadsheet file (default: "Open POA&M Items").'
        logger.info(text1 + text2)
        text1 = '  output-dir               = '
        text2 = '(required) the path of the output directory for synthesized OSCAL POAM .json file.'
        logger.info(text1 + text2)
        text1 = '  title                    = '
        text2 = '(required) the title for the POAM.'
        logger.info(text1 + text2)
        text1 = '  version                  = '
        text2 = '(required) the version of the POAM.'
        logger.info(text1 + text2)
        text1 = '  system-id                = '
        text2 = '(optional) the system identifier.'
        logger.info(text1 + text2)
        text1 = '  output-overwrite         = '
        text2 = '(optional) true [default] or false; replace existing output when true.'
        logger.info(text1 + text2)
        text1 = '  validate-required-fields = '
        text2 = '(optional) validation mode for required fields: on, warn [default], or off.'
        logger.info(text1 + text2)
        text1 = '  quiet                    = '
        text2 = '(optional) true or false [default]; suppress info messages when true.'
        logger.info(text1 + text2)
        logger.info('')
        logger.info('Expected columns in spreadsheet:')
        text1 = '                             '
        text2 = 'column "POAM ID" contains unique identifier for each POAM item (required).'
        logger.info(text1 + text2)
        text2 = 'column "Weakness Name" contains title/name of the weakness (required).'
        logger.info(text1 + text2)
        text2 = 'column "Weakness Description" contains description of the weakness (required).'
        logger.info(text1 + text2)
        text2 = 'column "Controls" contains related security control IDs (required).'
        logger.info(text1 + text2)
        text2 = 'column "Weakness Detector Source" contains source that detected the weakness (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Weakness Source Identifier" contains identifier from detection source (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Asset Identifier" contains identifier of affected asset (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Point of Contact" contains contact information for responsible party (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Resources Required" contains resources needed for remediation (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Overall Remediation Plan" contains the remediation plan description (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Original Detection Date" contains date weakness was first detected (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Scheduled Completion Date" contains target completion date (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Planned Milestones" contains milestone descriptions and dates (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Original Risk Rating" contains initial risk assessment (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Adjusted Risk Rating" contains adjusted risk assessment (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Risk Adjustment" contains rationale for risk adjustment (optional).'
        logger.info(text1 + text2)
        text2 = 'column "False Positive" contains yes/no indicator for false positive (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Operational Requirement" contains yes/no indicator for operational requirement (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Deviation Rationale" contains rationale for deviation (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Supporting Documents" contains references to supporting documentation (optional).'
        logger.info(text1 + text2)
        text2 = 'column "Comments" contains additional comments or notes (optional).'
        logger.info(text1 + text2)
        logger.info('')
        logger.info('Notes:')
        logger.info('  - The POAM template has the following structure, in keeping with FedRAMP xlsx format:')
        logger.info('    Row 1: Template title')
        logger.info('    Rows 2-4: Template instructions and metadata (ignored by this task)')
        logger.info('    Row 5: Column headers')
        logger.info('    Row 6+: Data rows (POAM items)')
        logger.info('  - POAM document metadata (title, version, system-id) comes from the configuration file,')
        logger.info('    not from the Excel template rows 1-4.')

    def configure(self) -> bool:
        """
        Configure the task.

        Returns:
            True if configuration successful, False otherwise
        """
        if not self._config:
            logger.error('Config section is missing')
            return False

        # Required parameters
        self._xlsx_file = self._config.get('xlsx-file')
        if not self._xlsx_file:
            logger.error('Missing required parameter: xlsx-file')
            return False

        self._output_dir = self._config.get('output-dir')
        if not self._output_dir:
            logger.error('Missing required parameter: output-dir')
            return False

        self._title = self._config.get('title')
        if not self._title:
            logger.error('Missing required parameter: title')
            return False

        self._version = self._config.get('version')
        if not self._version:
            logger.error('Missing required parameter: version')
            return False

        # Optional parameters
        self._work_sheet_name = self._config.get('work-sheet-name', 'Open POA&M Items')
        self._system_id = self._config.get('system-id')
        self._overwrite = self._config.getboolean('output-overwrite', True)
        self._validate_mode = self._config.get('validate-required-fields', 'warn')
        self._quiet = self._config.getboolean('quiet', False)

        return True

    def simulate(self) -> TaskOutcome:
        """Provide a simulated outcome."""
        return TaskOutcome('simulated-success')

    def execute(self) -> TaskOutcome:
        """Provide an executed outcome."""
        try:
            return self._execute()
        except Exception:
            logger.error(traceback.format_exc())
            return TaskOutcome('failure')

    def _execute(self) -> TaskOutcome:
        """Execute path core."""
        # Configure
        if not self.configure():
            return TaskOutcome('failure')

        # Setup output directory
        output_path = pathlib.Path(self._output_dir)
        output_path.mkdir(exist_ok=True, parents=True)

        # Setup Excel helper
        xlsx_path = pathlib.Path(self._xlsx_file)
        helper = PoamXlsxHelper()

        try:
            helper.load(xlsx_path, self._work_sheet_name)
        except FileNotFoundError as e:
            logger.error(str(e))
            return TaskOutcome('failure')
        except KeyError as e:
            logger.error(str(e))
            return TaskOutcome('failure')

        # Setup validator
        validator = PoamValidator(validate_mode=self._validate_mode)

        # Setup builder
        builder = PoamBuilder(self._timestamp, validator)

        # Process rows
        poam_items = []
        observations = []
        risks = []

        for row_num, row_data in helper.row_generator():
            # Validate row
            errors = validator.validate_row(row_num, row_data)
            if errors and self._validate_mode == 'on':
                logger.warning(f'Skipping row {row_num} due to validation errors')
                continue  # Skip invalid rows in strict mode; errors already stored in validator

            # Extract POAM ID
            poam_id = row_data.get(PoamXlsxHelper.POAM_ID, '')

            # Create OSCAL objects
            poam_item = builder.create_poam_item(poam_id, row_data)
            observation = builder.create_observation(poam_id, row_data, helper)
            risk = builder.create_risk(poam_id, row_data, helper)

            # Link objects
            builder.link_objects(poam_item, observation, risk)

            # Add to lists
            poam_items.append(poam_item)
            observations.append(observation)
            risks.append(risk)

        # Check validation results
        if not validator.log_validation_results():
            logger.error('Validation failed')
            return TaskOutcome('failure')

        if not poam_items:
            logger.error('No valid POAM items found in Excel file')
            return TaskOutcome('failure')

        # Create POAM
        poam = self._create_poam(poam_items, observations, risks)

        # Write output
        output_file = output_path / 'plan-of-action-and-milestones.json'
        if not self._overwrite and output_file.exists():
            logger.error(f'Output file already exists: {output_file}')
            return TaskOutcome('failure')

        poam.oscal_write(output_file)

        if not self._quiet:
            logger.info(f'Created POAM with {len(poam_items)} items')
            logger.info(f'Output: {output_file}')

        return TaskOutcome('success')

    def _create_poam(
        self, poam_items: List[PoamItem], observations: List[Observation], risks: List[Risk]
    ) -> PlanOfActionAndMilestones:
        """
        Create OSCAL PlanOfActionAndMilestones object.

        Args:
            poam_items: List of PoamItem objects
            observations: List of Observation objects
            risks: List of Risk objects

        Returns:
            PlanOfActionAndMilestones object
        """
        # Create metadata
        metadata = Metadata(
            title=self._title,
            version=self._version,
            **{'last-modified': self._timestamp, 'oscal-version': OSCAL_VERSION},
        )

        # Optional system-id
        system_id = None
        if self._system_id:
            system_id = SystemId(id=self._system_id, **{'identifier-type': 'https://ietf.org/rfc/rfc4122'})

        # Create POAM
        poam = PlanOfActionAndMilestones(
            uuid=str(uuid.uuid4()),
            metadata=metadata,
            observations=observations or None,
            risks=risks or None,
            **{'system-id': system_id, 'poam-items': poam_items},
        )

        return poam
Attributes¤
name = 'xlsx-to-oscal-poam' class-attribute instance-attribute ¤
Methods:¤
__init__(config_object) ¤

Initialize trestle task xlsx-to-oscal-poam.

Parameters:

Name Type Description Default
config_object Optional[SectionProxy]

Config section associated with the task.

required
Source code in trestle/tasks/xlsx_to_oscal_poam.py
826
827
828
829
830
831
832
833
834
def __init__(self, config_object: Optional[configparser.SectionProxy]) -> None:
    """
    Initialize trestle task xlsx-to-oscal-poam.

    Args:
        config_object: Config section associated with the task.
    """
    super().__init__(config_object)
    self._timestamp = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat()
configure() ¤

Configure the task.

Returns:

Type Description
bool

True if configuration successful, False otherwise

Source code in trestle/tasks/xlsx_to_oscal_poam.py
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
def configure(self) -> bool:
    """
    Configure the task.

    Returns:
        True if configuration successful, False otherwise
    """
    if not self._config:
        logger.error('Config section is missing')
        return False

    # Required parameters
    self._xlsx_file = self._config.get('xlsx-file')
    if not self._xlsx_file:
        logger.error('Missing required parameter: xlsx-file')
        return False

    self._output_dir = self._config.get('output-dir')
    if not self._output_dir:
        logger.error('Missing required parameter: output-dir')
        return False

    self._title = self._config.get('title')
    if not self._title:
        logger.error('Missing required parameter: title')
        return False

    self._version = self._config.get('version')
    if not self._version:
        logger.error('Missing required parameter: version')
        return False

    # Optional parameters
    self._work_sheet_name = self._config.get('work-sheet-name', 'Open POA&M Items')
    self._system_id = self._config.get('system-id')
    self._overwrite = self._config.getboolean('output-overwrite', True)
    self._validate_mode = self._config.get('validate-required-fields', 'warn')
    self._quiet = self._config.getboolean('quiet', False)

    return True
execute() ¤

Provide an executed outcome.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
974
975
976
977
978
979
980
def execute(self) -> TaskOutcome:
    """Provide an executed outcome."""
    try:
        return self._execute()
    except Exception:
        logger.error(traceback.format_exc())
        return TaskOutcome('failure')
print_info() ¤

Print the help string.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
def print_info(self) -> None:
    """Print the help string."""
    logger.info(f'Help information for {self.name} task.')
    logger.info('')
    logger.info('Purpose: Transform POAM spreadsheet to OSCAL POAM JSON format.')
    logger.info('')
    logger.info(f'Configuration flags sit under [task.{self.name}]:')
    text1 = '  xlsx-file                = '
    text2 = '(required) the path of the POAM spreadsheet file.'
    logger.info(text1 + text2)
    text1 = '  work-sheet-name          = '
    text2 = '(optional) the name of the work sheet in the spreadsheet file (default: "Open POA&M Items").'
    logger.info(text1 + text2)
    text1 = '  output-dir               = '
    text2 = '(required) the path of the output directory for synthesized OSCAL POAM .json file.'
    logger.info(text1 + text2)
    text1 = '  title                    = '
    text2 = '(required) the title for the POAM.'
    logger.info(text1 + text2)
    text1 = '  version                  = '
    text2 = '(required) the version of the POAM.'
    logger.info(text1 + text2)
    text1 = '  system-id                = '
    text2 = '(optional) the system identifier.'
    logger.info(text1 + text2)
    text1 = '  output-overwrite         = '
    text2 = '(optional) true [default] or false; replace existing output when true.'
    logger.info(text1 + text2)
    text1 = '  validate-required-fields = '
    text2 = '(optional) validation mode for required fields: on, warn [default], or off.'
    logger.info(text1 + text2)
    text1 = '  quiet                    = '
    text2 = '(optional) true or false [default]; suppress info messages when true.'
    logger.info(text1 + text2)
    logger.info('')
    logger.info('Expected columns in spreadsheet:')
    text1 = '                             '
    text2 = 'column "POAM ID" contains unique identifier for each POAM item (required).'
    logger.info(text1 + text2)
    text2 = 'column "Weakness Name" contains title/name of the weakness (required).'
    logger.info(text1 + text2)
    text2 = 'column "Weakness Description" contains description of the weakness (required).'
    logger.info(text1 + text2)
    text2 = 'column "Controls" contains related security control IDs (required).'
    logger.info(text1 + text2)
    text2 = 'column "Weakness Detector Source" contains source that detected the weakness (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Weakness Source Identifier" contains identifier from detection source (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Asset Identifier" contains identifier of affected asset (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Point of Contact" contains contact information for responsible party (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Resources Required" contains resources needed for remediation (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Overall Remediation Plan" contains the remediation plan description (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Original Detection Date" contains date weakness was first detected (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Scheduled Completion Date" contains target completion date (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Planned Milestones" contains milestone descriptions and dates (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Original Risk Rating" contains initial risk assessment (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Adjusted Risk Rating" contains adjusted risk assessment (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Risk Adjustment" contains rationale for risk adjustment (optional).'
    logger.info(text1 + text2)
    text2 = 'column "False Positive" contains yes/no indicator for false positive (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Operational Requirement" contains yes/no indicator for operational requirement (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Deviation Rationale" contains rationale for deviation (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Supporting Documents" contains references to supporting documentation (optional).'
    logger.info(text1 + text2)
    text2 = 'column "Comments" contains additional comments or notes (optional).'
    logger.info(text1 + text2)
    logger.info('')
    logger.info('Notes:')
    logger.info('  - The POAM template has the following structure, in keeping with FedRAMP xlsx format:')
    logger.info('    Row 1: Template title')
    logger.info('    Rows 2-4: Template instructions and metadata (ignored by this task)')
    logger.info('    Row 5: Column headers')
    logger.info('    Row 6+: Data rows (POAM items)')
    logger.info('  - POAM document metadata (title, version, system-id) comes from the configuration file,')
    logger.info('    not from the Excel template rows 1-4.')
set_timestamp(timestamp) ¤

Set the timestamp.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
836
837
838
def set_timestamp(self, timestamp: str) -> None:
    """Set the timestamp."""
    self._timestamp = timestamp
simulate() ¤

Provide a simulated outcome.

Source code in trestle/tasks/xlsx_to_oscal_poam.py
970
971
972
def simulate(self) -> TaskOutcome:
    """Provide a simulated outcome."""
    return TaskOutcome('simulated-success')

handler: python