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

import (
	"strings"
	"time"

	"golang.org/x/crypto/ssh"

	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

var (
	certsDB     = "certs"
	issuedTable = "issued_certs"
)

type mongoDB struct {
	collection *mgo.Collection
	session    *mgo.Session
}

func parseMongoConfig(config string) *mgo.DialInfo {
	s := strings.SplitN(config, ":", 4)
	_, user, passwd, hosts := s[0], s[1], s[2], s[3]
	d := &mgo.DialInfo{
		Addrs:    strings.Split(hosts, ","),
		Username: user,
		Password: passwd,
		Database: certsDB,
		Timeout:  time.Second * 5,
	}
	return d
}

// NewMongoStore returns a MongoDB CertStorer.
func NewMongoStore(config string) (CertStorer, error) {
	session, err := mgo.DialWithInfo(parseMongoConfig(config))
	if err != nil {
		return nil, err
	}
	c := session.DB(certsDB).C(issuedTable)
	return &mongoDB{
		collection: c,
		session:    session,
	}, nil
}

func (m *mongoDB) Get(id string) (*CertRecord, error) {
	if err := m.session.Ping(); err != nil {
		return nil, err
	}
	c := &CertRecord{}
	err := m.collection.Find(bson.M{"keyid": id}).One(c)
	return c, err
}

func (m *mongoDB) SetCert(cert *ssh.Certificate) error {
	r := parseCertificate(cert)
	return m.SetRecord(r)
}

func (m *mongoDB) SetRecord(record *CertRecord) error {
	if err := m.session.Ping(); err != nil {
		return err
	}
	return m.collection.Insert(record)
}

func (m *mongoDB) List() ([]*CertRecord, error) {
	if err := m.session.Ping(); err != nil {
		return nil, err
	}
	var result []*CertRecord
	m.collection.Find(nil).All(&result)
	return result, nil
}

func (m *mongoDB) Revoke(id string) error {
	if err := m.session.Ping(); err != nil {
		return err
	}
	return m.collection.Update(bson.M{"keyid": id}, bson.M{"$set": bson.M{"revoked": true}})
}

func (m *mongoDB) GetRevoked() ([]*CertRecord, error) {
	if err := m.session.Ping(); err != nil {
		return nil, err
	}
	var result []*CertRecord
	err := m.collection.Find(bson.M{"expires": bson.M{"$gte": time.Now().UTC()}, "revoked": true}).All(&result)
	return result, err
}

func (m *mongoDB) Close() error {
	m.session.Close()
	return nil
}