Skip to content
quarry Artifact [7ad03adc7a]
Login

Artifact [7ad03adc7a]

Artifact 7ad03adc7a8d57ea8e28f598483315c9be728f78873d09126305dda59e95651d:


package oltp

import (
	"database/sql"
	"errors"
)

// workerTokenSchema is what the forge knows of the worker tokens it
// minted: a SHA-256 of the value (never the value) against the token's
// id and worker group. It lets the bridge tell a token's holder which
// repository the token is for. A token minted before the table existed
// is simply not in it.
const workerTokenSchema = `
CREATE TABLE IF NOT EXISTS worker_token_ledger (
	hash         TEXT PRIMARY KEY, -- hex SHA-256 of the bearer
	token_id     TEXT NOT NULL,
	worker_group TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS worker_token_ledger_id ON worker_token_ledger (token_id);`

// RecordWorkerToken notes a minted token's group under the hash of its value.
func (d *DB) RecordWorkerToken(hash, tokenID, group string) error {
	if hash == "" || tokenID == "" || group == "" {
		return errors.New("oltp: a worker token record needs a hash, an id and a group")
	}
	_, err := d.w.Exec(`INSERT OR REPLACE INTO worker_token_ledger (hash, token_id, worker_group) VALUES (?, ?, ?)`, hash, tokenID, group)
	return err
}

// ForgetWorkerToken drops a revoked token's record.
func (d *DB) ForgetWorkerToken(tokenID string) error {
	_, err := d.w.Exec(`DELETE FROM worker_token_ledger WHERE token_id = ?`, tokenID)
	return err
}

// WorkerTokenGroup is the group recorded for a value's hash, false when
// the forge has no record of it.
func (d *DB) WorkerTokenGroup(hash string) (string, bool) {
	var g string
	err := d.db.QueryRow(`SELECT worker_group FROM worker_token_ledger WHERE hash = ?`, hash).Scan(&g)
	if errors.Is(err, sql.ErrNoRows) || err != nil {
		return "", false
	}
	return g, true
}