aboutsummaryrefslogtreecommitdiff
path: root/server/store/mem.go
blob: 54aa9655d011794bb4446d788129ba7a6740097e (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
package store

import (
	"fmt"
	"sync"
	"time"

	"golang.org/x/crypto/ssh"
)

type memoryStore struct {
	sync.Mutex
	certs map[string]*CertRecord
}

func (ms *memoryStore) Get(id string) (*CertRecord, error) {
	ms.Lock()
	defer ms.Unlock()
	r, ok := ms.certs[id]
	if !ok {
		return nil, fmt.Errorf("unknown cert %s", id)
	}
	return r, nil
}

func (ms *memoryStore) SetCert(cert *ssh.Certificate) error {
	return ms.SetRecord(parseCertificate(cert))
}

func (ms *memoryStore) SetRecord(record *CertRecord) error {
	ms.Lock()
	defer ms.Unlock()
	ms.certs[record.KeyID] = record
	return nil
}

func (ms *memoryStore) List(includeExpired bool) ([]*CertRecord, error) {
	var records []*CertRecord
	ms.Lock()
	defer ms.Unlock()

	for _, value := range ms.certs {
		if !includeExpired && value.Expires.Before(time.Now().UTC()) {
			continue
		}
		records = append(records, value)
	}
	return records, nil
}

func (ms *memoryStore) Revoke(id string) error {
	r, err := ms.Get(id)
	if err != nil {
		return err
	}
	r.Revoked = true
	ms.SetRecord(r)
	return nil
}

func (ms *memoryStore) GetRevoked() ([]*CertRecord, error) {
	var revoked []*CertRecord
	all, _ := ms.List(false)
	for _, r := range all {
		if r.Revoked {
			revoked = append(revoked, r)
		}
	}
	return revoked, nil
}

func (ms *memoryStore) Close() error {
	ms.Lock()
	defer ms.Unlock()
	ms.certs = nil
	return nil
}

func (ms *memoryStore) clear() {
	for k := range ms.certs {
		delete(ms.certs, k)
	}
}

// NewMemoryStore returns an in-memory CertStorer.
func NewMemoryStore() CertStorer {
	return &memoryStore{
		certs: make(map[string]*CertRecord),
	}
}