2025-02-20 20:45:49 -05:00
|
|
|
package keydirectory
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto"
|
2025-02-20 22:53:18 -05:00
|
|
|
"crypto/x509"
|
2025-02-20 20:45:49 -05:00
|
|
|
"database/sql"
|
|
|
|
|
|
|
|
"github.com/common-fate/httpsig/verifier"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type dbWrapper struct {
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func InitSqlite(dbPath string) (*dbWrapper, error) {
|
|
|
|
db, err := sql.Open("sqlite3", dbPath)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return &dbWrapper{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
createStmt := `
|
|
|
|
create table
|
|
|
|
if not exists
|
2025-02-20 23:06:04 -05:00
|
|
|
keys(keyId text not null primary key, userId text, publicKey blob)
|
2025-02-20 20:45:49 -05:00
|
|
|
`
|
|
|
|
|
|
|
|
_, err = db.Exec(createStmt)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return &dbWrapper{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &dbWrapper{db}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dir *dbWrapper) GetKey(ctx context.Context, keyId string, _ string) (verifier.Algorithm, error) {
|
|
|
|
db := dir.db
|
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
query := "select userId, publicKey from keys where keyId = ?"
|
2025-02-20 20:45:49 -05:00
|
|
|
|
|
|
|
stmt, err := db.Prepare(query)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer stmt.Close()
|
|
|
|
|
|
|
|
var userId string
|
|
|
|
var keyBytes []byte
|
|
|
|
|
|
|
|
row := stmt.QueryRow(keyId)
|
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
err = row.Scan(&userId, &keyBytes)
|
2025-02-20 20:45:49 -05:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
publicKey, err := x509.ParsePKIXPublicKey(keyBytes)
|
2025-02-20 20:45:49 -05:00
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2025-02-20 20:45:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
keyEntry := keyEntry{
|
|
|
|
UserId: userId,
|
|
|
|
PublicKey: publicKey,
|
|
|
|
}
|
|
|
|
|
|
|
|
return keyEntry.toAlg()
|
|
|
|
}
|
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
func (dir *dbWrapper) RegisterKey(key crypto.PublicKey, userId string) (string, error) {
|
2025-02-20 20:45:49 -05:00
|
|
|
db := dir.db
|
|
|
|
|
|
|
|
keyId, err := generateKeyId()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
stmt := "insert into keys(keyId, userId, publicKey) values (?, ?, ?)"
|
2025-02-20 20:45:49 -05:00
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
keyBytes, err := x509.MarshalPKIXPublicKey(key)
|
2025-02-20 20:45:49 -05:00
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
2025-02-20 20:45:49 -05:00
|
|
|
}
|
|
|
|
|
2025-02-20 22:53:18 -05:00
|
|
|
_, err = db.Exec(stmt, keyId, userId, keyBytes)
|
2025-02-20 20:45:49 -05:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return keyId, nil
|
|
|
|
}
|