summaryrefslogtreecommitdiff
path: root/internal/authentication/cached.go
blob: b84d988bffedb98866138f374903610c83374984 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package authentication

import (
	"crypto/hmac"
	"crypto/rand"
	"fmt"
	"hash"
	"sync"
	"time"
)

// NewCredentialCacheHMAC creates a new CredentialCacheHMAC with a given hash.Hash func and lifespan.
func NewCredentialCacheHMAC(h func() hash.Hash, lifespan time.Duration) *CredentialCacheHMAC {
	secret := make([]byte, h().BlockSize())

	_, _ = rand.Read(secret)

	return &CredentialCacheHMAC{
		mu:       sync.Mutex{},
		hash:     hmac.New(h, secret),
		lifespan: lifespan,

		values: map[string]CachedCredential{},
	}
}

// CredentialCacheHMAC implements in-memory credential caching using a HMAC function and effective lifespan.
type CredentialCacheHMAC struct {
	mu   sync.Mutex
	hash hash.Hash

	lifespan time.Duration

	values map[string]CachedCredential
}

// Valid checks the cache for results for a given username and password in the cache and returns two booleans. The valid
// return value is indicative if the credential cache had an exact match, and the ok return value returns true if a
// current cached value exists within the cache.
func (c *CredentialCacheHMAC) Valid(username, password string) (valid, ok bool) {
	c.mu.Lock()

	defer c.mu.Unlock()

	var (
		entry CachedCredential
		err   error
	)

	if entry, ok = c.values[username]; ok {
		if entry.expires.Before(time.Now()) {
			delete(c.values, username)

			return false, false
		}
	}

	var value []byte

	if value, err = c.sum(username, password); err != nil {
		return false, false
	}

	valid = hmac.Equal(value, entry.value)

	c.hash.Reset()

	return valid, true
}

func (c *CredentialCacheHMAC) sum(username, password string) (sum []byte, err error) {
	defer c.hash.Reset()

	if _, err = c.hash.Write([]byte(password)); err != nil {
		return nil, fmt.Errorf("error occurred calculating cache hmac: %w", err)
	}

	if _, err = c.hash.Write([]byte(username)); err != nil {
		return nil, fmt.Errorf("error occurred calculating cache hmac: %w", err)
	}

	return c.hash.Sum(nil), nil
}

// Put a new credential combination into the cache.
func (c *CredentialCacheHMAC) Put(username, password string) (err error) {
	c.mu.Lock()

	defer c.mu.Unlock()

	var value []byte

	if value, err = c.sum(username, password); err != nil {
		return err
	}

	c.values[username] = CachedCredential{expires: time.Now().Add(c.lifespan), value: value}

	return nil
}

// CachedCredential is a cached credential which has an expiration and checksum value.
type CachedCredential struct {
	expires time.Time
	value   []byte
}