github.com/hashicorp/vault/sdk@v0.13.0/framework/identity.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package framework
     5  
     6  import (
     7  	"errors"
     8  
     9  	"github.com/hashicorp/errwrap"
    10  	"github.com/hashicorp/vault/sdk/helper/identitytpl"
    11  	"github.com/hashicorp/vault/sdk/logical"
    12  )
    13  
    14  // PopulateIdentityTemplate takes a template string, an entity ID, and an
    15  // instance of system view. It will query system view for information about the
    16  // entity and use the resulting identity information to populate the template
    17  // string.
    18  func PopulateIdentityTemplate(tpl string, entityID string, sysView logical.SystemView) (string, error) {
    19  	entity, err := sysView.EntityInfo(entityID)
    20  	if err != nil {
    21  		return "", err
    22  	}
    23  	if entity == nil {
    24  		return "", errors.New("no entity found")
    25  	}
    26  
    27  	groups, err := sysView.GroupsForEntity(entityID)
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  
    32  	input := identitytpl.PopulateStringInput{
    33  		String: tpl,
    34  		Entity: entity,
    35  		Groups: groups,
    36  		Mode:   identitytpl.ACLTemplating,
    37  	}
    38  
    39  	_, out, err := identitytpl.PopulateString(input)
    40  	if err != nil {
    41  		return "", err
    42  	}
    43  
    44  	return out, nil
    45  }
    46  
    47  // ValidateIdentityTemplate takes a template string and returns if the string is
    48  // a valid identity template.
    49  func ValidateIdentityTemplate(tpl string) (bool, error) {
    50  	hasTemplating, _, err := identitytpl.PopulateString(identitytpl.PopulateStringInput{
    51  		Mode:              identitytpl.ACLTemplating,
    52  		ValidityCheckOnly: true,
    53  		String:            tpl,
    54  	})
    55  	if err != nil {
    56  		return false, errwrap.Wrapf("failed to validate policy templating: {{err}}", err)
    57  	}
    58  
    59  	return hasTemplating, nil
    60  }