<commit_before>package appId

import (
	"sync"

	"github.com/hashicorp/vault/helper/salt"
	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
)

func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
	b, err := Backend(conf)
	if err != nil {
		return nil, err
	}
	return b.Setup(conf)
}

func Backend(conf *logical.BackendConfig) (*framework.Backend, error) {
	var b backend
	b.MapAppId = &framework.PolicyMap{
		PathMap: framework.PathMap{
			Name: "app-id",
			Schema: map[string]*framework.FieldSchema{
				"display_name": &framework.FieldSchema{
					Type:        framework.TypeString,
					Description: "A name to map to this app ID for logs.",
				},

				"value": &framework.FieldSchema{
					Type:        framework.TypeString,
					Description: "Policies for the app ID.",
				},
			},
		},
		DefaultKey: "default",
	}

	b.MapUserId = &framework.PathMap{
		Name: "user-id",
		Schema: map[string]*framework.FieldSchema{
			"cidr_block": &framework.FieldSchema{
				Type:        framework.TypeString,
				Description: "If not blank, restricts auth by this CIDR block",
			},

			"value": &framework.FieldSchema{
				Type:        framework.TypeString,
				Description: "App IDs that this user associates with.",
			},
		},
	}

	b.Backend = &framework.Backend{
		Help: backendHelp,

		PathsSpecial: &logical.Paths{
			Unauthenticated: []string{
				"login",
				"login/*",
			},
		},

		Paths: framework.PathAppend([]*framework.Path{
			pathLogin(&b),
			pathLoginWithAppIDPath(&b),
		},
			b.MapAppId.Paths(),
			b.MapUserId.Paths(),
		),

		AuthRenew: b.pathLoginRenew,

		Invalidate: b.invalidate,
	}

	b.view = conf.StorageView

	return b.Backend, nil
}

type backend struct {
	*framework.Backend

	salt      *salt.Salt
	SaltMutex sync.RWMutex
	view      logical.Storage
	MapAppId  *framework.PolicyMap
	MapUserId *framework.PathMap
}

func (b *backend) Salt() (*salt.Salt, error) {
	b.SaltMutex.RLock()
	if b.salt != nil {
		defer b.SaltMutex.RUnlock()
		return b.salt, nil
	}
	b.SaltMutex.RUnlock()
	b.SaltMutex.Lock()
	defer b.SaltMutex.Unlock()
	if b.salt != nil {
		return b.salt, nil
	}
	salt, err := salt.NewSalt(b.view, &salt.Config{
		HashFunc: salt.SHA1Hash,
		Location: salt.DefaultLocation,
	})
	if err != nil {
		return nil, err
	}
	b.salt = salt
	b.MapAppId.SaltFunc = b.Salt
	b.MapUserId.SaltFunc = b.Salt

	return salt, nil
}

func (b *backend) invalidate(key string) {
	switch key {
	case salt.DefaultLocation:
		b.SaltMutex.Lock()
		defer b.SaltMutex.Unlock()
		b.salt = nil
	}
}

const backendHelp = `
The App ID credential provider is used to perform authentication from
within applications or machine by pairing together two hard-to-guess
unique pieces of information: a unique app ID, and a unique user ID.

The goal of this credential provider is to allow elastic users
(dynamic machines, containers, etc.) to authenticate with Vault without
having to store passwords outside of Vault. It is a single method of
solving the chicken-and-egg problem of setting up Vault access on a machine.
With this provider, nobody except the machine itself has access to both
pieces of information necessary to authenticate. For example:
configuration management will have the app IDs, but the machine itself
will detect its user ID based on some unique machine property such as a
MAC address (or a hash of it with some salt).

An example, real world process for using this provider:

  1. Create unique app IDs (UUIDs work well) and map them to policies.
     (Path: map/app-id/<app-id>)<commit_msg>Fix instantiation of salt funcs in app-id structs<commit_after>package appId

import (
	"sync"

	"github.com/hashicorp/vault/helper/salt"
	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
)

func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
	b, err := Backend(conf)
	if err != nil {
		return nil, err
	}
	return b.Setup(conf)
}

func Backend(conf *logical.BackendConfig) (*framework.Backend, error) {
	var b backend
	b.MapAppId = &framework.PolicyMap{
		PathMap: framework.PathMap{
			Name: "app-id",
			Schema: map[string]*framework.FieldSchema{
				"display_name": &framework.FieldSchema{
					Type:        framework.TypeString,
					Description: "A name to map to this app ID for logs.",
				},

				"value": &framework.FieldSchema{
					Type:        framework.TypeString,
					Description: "Policies for the app ID.",
				},
			},
		},
		DefaultKey: "default",
	}

	b.MapUserId = &framework.PathMap{
		Name: "user-id",
		Schema: map[string]*framework.FieldSchema{
			"cidr_block": &framework.FieldSchema{
				Type:        framework.TypeString,
				Description: "If not blank, restricts auth by this CIDR block",
			},

			"value": &framework.FieldSchema{
				Type:        framework.TypeString,
				Description: "App IDs that this user associates with.",
			},
		},
	}

	b.Backend = &framework.Backend{
		Help: backendHelp,

		PathsSpecial: &logical.Paths{
			Unauthenticated: []string{
				"login",
				"login/*",
			},
		},

		Paths: framework.PathAppend([]*framework.Path{
			pathLogin(&b),
			pathLoginWithAppIDPath(&b),
		},
			b.MapAppId.Paths(),
			b.MapUserId.Paths(),
		),

		AuthRenew: b.pathLoginRenew,

		Invalidate: b.invalidate,
	}

	b.view = conf.StorageView

	b.MapAppId.SaltFunc = b.Salt
	b.MapUserId.SaltFunc = b.Salt

	return b.Backend, nil
}

type backend struct {
	*framework.Backend

	salt      *salt.Salt
	SaltMutex sync.RWMutex
	view      logical.Storage
	MapAppId  *framework.PolicyMap
	MapUserId *framework.PathMap
}

func (b *backend) Salt() (*salt.Salt, error) {
	b.SaltMutex.RLock()
	if b.salt != nil {
		defer b.SaltMutex.RUnlock()
		return b.salt, nil
	}
	b.SaltMutex.RUnlock()
	b.SaltMutex.Lock()
	defer b.SaltMutex.Unlock()
	if b.salt != nil {
		return b.salt, nil
	}
	salt, err := salt.NewSalt(b.view, &salt.Config{
		HashFunc: salt.SHA1Hash,
		Location: salt.DefaultLocation,
	})
	if err != nil {
		return nil, err
	}
	b.salt = salt
	return salt, nil
}

func (b *backend) invalidate(key string) {
	switch key {
	case salt.DefaultLocation:
		b.SaltMutex.Lock()
		defer b.SaltMutex.Unlock()
		b.salt = nil
	}
}

const backendHelp = `
The App ID credential provider is used to perform authentication from
within applications or machine by pairing together two hard-to-guess
unique pieces of information: a unique app ID, and a unique user ID.

The goal of this credential provider is to allow elastic users
(dynamic machines, containers, etc.) to authenticate with Vault without
having to store passwords outside of Vault. It is a single method of
solving the chicken-and-egg problem of setting up Vault access on a machine.
With this provider, nobody except the machine itself has access to both
pieces of information necessary to authenticate. For example:
configuration management will have the app IDs, but the machine itself
will detect its user ID based on some unique machine property such as a
MAC address (or a hash of it with some salt).

An example, real world process for using this provider:

  1. Create unique app IDs (UUIDs work well) and map them to policies.
     (Path: map/app-id/<app-id>)
{'fraction_non_alphanumeric': 0.1096062552359676, 'fraction_numerical': 0.0005585032113934655, 'mean_word_length': 3.582853486884197, 'pattern_counts': {'":': 8, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4639468', 'n_tokens_mistral': 2609, 'n_tokens_neox': 2352, 'n_words': 722}