1package openldap
2
3import (
4	"context"
5	"fmt"
6	"path"
7	"time"
8
9	"github.com/hashicorp/vault/sdk/logical"
10)
11
12type dynamicRole struct {
13	// required fields
14	Name         string `json:"name"          mapstructure:"name"`
15	CreationLDIF string `json:"creation_ldif" mapstructure:"creation_ldif"`
16	DeletionLDIF string `json:"deletion_ldif" mapstructure:"deletion_ldif"`
17
18	// optional fields
19	RollbackLDIF     string        `json:"rollback_ldif"               mapstructure:"rollback_ldif,omitempty"`
20	UsernameTemplate string        `json:"username_template,omitempty" mapstructure:"username_template,omitempty"`
21	DefaultTTL       time.Duration `json:"default_ttl,omitempty"       mapstructure:"default_ttl,omitempty"`
22	MaxTTL           time.Duration `json:"max_ttl,omitempty"           mapstructure:"max_ttl,omitempty"`
23}
24
25func retrieveDynamicRole(ctx context.Context, s logical.Storage, roleName string) (*dynamicRole, error) {
26	entry, err := s.Get(ctx, path.Join(dynamicRolePath, roleName))
27	if err != nil {
28		return nil, err
29	}
30	if entry == nil {
31		return nil, nil
32	}
33
34	result := new(dynamicRole)
35	if err := entry.DecodeJSON(result); err != nil {
36		return nil, err
37	}
38
39	return result, nil
40}
41
42func storeDynamicRole(ctx context.Context, s logical.Storage, role *dynamicRole) error {
43	if role.Name == "" {
44		return fmt.Errorf("missing role name")
45	}
46	entry, err := logical.StorageEntryJSON(path.Join(dynamicRolePath, role.Name), role)
47	if err != nil {
48		return fmt.Errorf("unable to marshal storage entry: %w", err)
49	}
50
51	err = s.Put(ctx, entry)
52	if err != nil {
53		return fmt.Errorf("failed to store dynamic role: %w", err)
54	}
55	return nil
56}
57
58func deleteDynamicRole(ctx context.Context, s logical.Storage, roleName string) error {
59	if roleName == "" {
60		return fmt.Errorf("missing role name")
61	}
62	return s.Delete(ctx, path.Join(dynamicRolePath, roleName))
63}
64