Skip to content
Snippets Groups Projects
SAMLMetadata.pm 11.84 KiB
package IdPAccountManager::SAMLMetadata;

use strict;
use warnings;

use English qw(-no_match_vars);
use XML::LibXML;

use IdPAccountManager::Tools;

sub new {
    my ($pkg, %args) = @_;

    die "missing argument 'file'" unless defined $args{file};
    die "non-existing file $args{file}" unless -f $args{file};
    die "non-readable file $args{file}" unless -r $args{file};

    open(my $handle, '<', $args{file})
        or die "failed to open file $args{file}: $ERRNO";

    my $parser = XML::LibXML->new();
    die "Failed to initialize XML parser" unless $parser;

    my $doc;
    eval { $doc = $parser->parse_fh($handle) };
    die "Failed to parse file $args{file}: $EVAL_ERROR"
        if $EVAL_ERROR;

    die "Failed to parse file $args{file}: $EVAL_ERROR"
        unless $doc;

    my $root = $doc->documentElement();
    my $type = $root->nodeName();

    die "incorrect root element type '$type' for file $args{file}, should be
        'EntitiesDescriptor'" unless $type =~ /EntitiesDescriptor$/;

    my $self = {
        file => $args{file},
        doc  => $doc
    };

    bless $self, $pkg;

    return $self;
}

## Parse XML structure of metadata to fill a hashref
sub parse {
    my ($self, %args) = @_;

    my %parser_args = (
        metadata_as_xml    => $self->{doc},
        filter_entity_type => 'sp'
    );

    if ($args{filter_entity_id}) {
        $parser_args{filter_entity_id} = $args{filter_entity_id};
    }

    $self->{federation_metadata_as_hashref} =
      $self->_parse_saml_metadata(%parser_args);

    die "Failed to parse federation metadata"
        unless defined $self->{federation_metadata_as_hashref};

    return 1;
}

## Dumps the SAML metadata content