package store import ( "context" "atlas9.dev/c/core" "atlas9.dev/c/core/dbi" "atlas9.dev/c/core/envelope" "atlas9.dev/c/demo/lib/access" ) // SqliteDekStore is the SQLite implementation of [envelope.DekStore]. type SqliteDekStore struct { db dbi.DBI guard access.Guard } var _ envelope.DekStore = (*SqliteDekStore)(nil) func NewSqliteDekStore(db dbi.DBI, guard access.Guard) *SqliteDekStore { return &SqliteDekStore{db: db, guard: guard} } // ForTenant returns the active DEK for the tenant. Returns core.ErrNotFound if none exists. func (s *SqliteDekStore) ForTenant(ctx context.Context, tenant core.ID) (envelope.DEK, error) { if err := s.guard.Check(ctx, envelope.Cap_Dek_Use, tenant, ""); err != nil { return envelope.DEK{}, err } var dek envelope.DEK err := dbi.Get(ctx, s.db, &dek, ` SELECT id, wrapped_key FROM deks WHERE tenant = $1 AND retired_at IS NULL ORDER BY id DESC LIMIT 1 `, tenant) if err != nil { return envelope.DEK{}, err } return dek, nil } func (s *SqliteDekStore) Create(ctx context.Context, tenant core.ID, wrappedKey []byte) (envelope.DEK, error) { if err := s.guard.Check(ctx, envelope.Cap_Dek_Create, tenant, ""); err != nil { return envelope.DEK{}, err } id := core.NewID("dek") _, err := s.db.Exec(ctx, ` INSERT INTO deks (id, tenant, wrapped_key) VALUES ($1, $2, $3) `, id, tenant, wrappedKey) if err != nil { return envelope.DEK{}, err } return envelope.DEK{ID: id, WrappedKey: wrappedKey}, nil }