File: certificates.go

package info (click to toggle)
incus 6.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,392 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (89 lines) | stat: -rw-r--r-- 2,343 bytes parent folder | download | duplicates (6)
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
//go:build linux && cgo && !agent

package db

import (
	"context"

	"github.com/lxc/incus/v6/internal/server/certificate"
	"github.com/lxc/incus/v6/internal/server/db/cluster"
	"github.com/lxc/incus/v6/internal/server/db/query"
)

// UpdateCertificate updates a certificate in the db.
func (db *DB) UpdateCertificate(ctx context.Context, fingerprint string, cert cluster.Certificate, projectNames []string) error {
	err := db.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *ClusterTx) error {
		id, err := cluster.GetCertificateID(ctx, tx.Tx(), fingerprint)
		if err != nil {
			return err
		}

		err = cluster.UpdateCertificate(ctx, tx.Tx(), fingerprint, cert)
		if err != nil {
			return err
		}

		return cluster.UpdateCertificateProjects(ctx, tx.Tx(), int(id), projectNames)
	})

	return err
}

// GetCertificates returns all available local certificates.
func (n *NodeTx) GetCertificates(ctx context.Context) ([]cluster.Certificate, error) {
	type cert struct {
		fingerprint string
		certType    certificate.Type
		name        string
		certificate string
	}

	sql := "SELECT fingerprint, type, name, certificate FROM certificates"
	dbCerts := []cert{}
	err := query.Scan(ctx, n.tx, sql, func(scan func(dest ...any) error) error {
		dbCert := cert{}

		err := scan(&dbCert.fingerprint, &dbCert.certType, &dbCert.name, &dbCert.certificate)
		if err != nil {
			return err
		}

		dbCerts = append(dbCerts, dbCert)

		return nil
	})
	if err != nil {
		return nil, err
	}

	certs := make([]cluster.Certificate, 0, len(dbCerts))
	for _, dbCert := range dbCerts {
		certs = append(certs, cluster.Certificate{
			Fingerprint: dbCert.fingerprint,
			Type:        dbCert.certType,
			Name:        dbCert.name,
			Certificate: dbCert.certificate,
		})
	}

	return certs, nil
}

// ReplaceCertificates removes all existing certificates from the local certificates table and replaces them with
// the ones provided.
func (n *NodeTx) ReplaceCertificates(certs []cluster.Certificate) error {
	_, err := n.tx.Exec("DELETE FROM certificates")
	if err != nil {
		return err
	}

	sql := "INSERT INTO certificates (fingerprint, type, name, certificate) VALUES(?,?,?,?)"
	for _, cert := range certs {
		_, err = n.tx.Exec(sql, cert.Fingerprint, cert.Type, cert.Name, cert.Certificate)
		if err != nil {
			return err
		}
	}

	return nil
}