Repository navigation
Expand file tree
/
Copy pathstore_postgres.go
More file actions
362 lines (329 loc) · 12.1 KB
/
Copy pathstore_postgres.go
File metadata and controls
362 lines (329 loc) · 12.1 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package agentauth
import (
"context"
"database/sql"
"errors"
"strings"
"time"
"github.com/xraph/grove"
"github.com/xraph/grove/drivers/pgdriver"
"github.com/xraph/authsome/id"
)
// PostgresStore implements agentauth.Store using the Grove ORM with PostgreSQL.
type PostgresStore struct {
db *grove.DB
pg *pgdriver.PgDB
}
// NewPostgresStore creates a new PostgreSQL-backed agentauth store.
func NewPostgresStore(db *grove.DB) *PostgresStore {
return &PostgresStore{
db: db,
pg: pgdriver.Unwrap(db),
}
}
// Compile-time interface check.
var _ Store = (*PostgresStore)(nil)
// ──────────────────────────────────────────────────
// Agent methods
// ──────────────────────────────────────────────────
func (s *PostgresStore) CreateAgent(ctx context.Context, a *Agent) error {
m := fromAgent(a)
_, err := s.pg.NewInsert(m).Exec(ctx)
return agentauthPgError(err)
}
func (s *PostgresStore) GetAgent(ctx context.Context, agentID id.AgentID) (*Agent, error) {
m := new(agentModel)
err := s.pg.NewSelect(m).
Where("id = ?", agentID.String()).
Scan(ctx)
if err != nil {
return nil, agentauthPgError(err)
}
return toAgent(m)
}
func (s *PostgresStore) GetAgentByClientID(ctx context.Context, clientID string) (*Agent, error) {
m := new(agentModel)
err := s.pg.NewSelect(m).
Where("client_id = ?", clientID).
Scan(ctx)
if err != nil {
return nil, agentauthPgError(err)
}
return toAgent(m)
}
func (s *PostgresStore) UpdateAgent(ctx context.Context, a *Agent) error {
m := fromAgent(a)
res, err := s.pg.NewUpdate(m).WherePK().Exec(ctx)
if err != nil {
return agentauthPgError(err)
}
rows, _ := res.RowsAffected() //nolint:errcheck // driver always supports RowsAffected
if rows == 0 {
return ErrNotFound
}
return nil
}
func (s *PostgresStore) ListAgents(ctx context.Context, appID id.AppID, orgID id.OrgID) ([]*Agent, error) {
var models []agentModel
q := s.pg.NewSelect(&models).Where("app_id = ?", appID.String())
if !orgID.IsNil() {
q = q.Where("org_id = ?", orgID.String())
}
if err := q.OrderExpr("created_at ASC").Scan(ctx); err != nil {
return nil, agentauthPgError(err)
}
out := make([]*Agent, 0, len(models))
for i := range models {
a, err := toAgent(&models[i])
if err != nil {
return nil, err
}
out = append(out, a)
}
return out, nil
}
// ──────────────────────────────────────────────────
// Agent grant methods
// ──────────────────────────────────────────────────
func (s *PostgresStore) CreateAgentGrant(ctx context.Context, g *AgentGrant) error {
m, err := fromAgentGrant(g)
if err != nil {
return err
}
_, err = s.pg.NewInsert(m).Exec(ctx)
return agentauthPgError(err)
}
func (s *PostgresStore) GetAgentGrant(ctx context.Context, grantID id.AgentGrantID) (*AgentGrant, error) {
m := new(agentGrantModel)
err := s.pg.NewSelect(m).
Where("id = ?", grantID.String()).
Scan(ctx)
if err != nil {
return nil, agentauthPgError(err)
}
return toAgentGrant(m)
}
// GetActiveGrant returns the most recently created matching grant when more
// than one exists. Duplicates are the normal state, not an edge case:
// CreateGrant always inserts a fresh grant rather than upserting, so an
// ordinary re-consent leaves an older active grant for the same
// agent+user+org triple lying around alongside the new one. Without an
// explicit order, which row a plain "one matching row" query returns is
// backend-specific — Postgres/SQLite/Mongo have no defined tie-break and
// MemoryStore's map iteration is randomized — so the four backends would
// disagree about which grant is "the" active one. Ordering by CreatedAt
// DESC makes all four agree: the newest grant wins.
func (s *PostgresStore) GetActiveGrant(ctx context.Context, agentID id.AgentID, userID id.UserID, orgID id.OrgID) (*AgentGrant, error) {
m := new(agentGrantModel)
err := s.pg.NewSelect(m).
Where("agent_id = ?", agentID.String()).
Where("user_id = ?", userID.String()).
Where("org_id = ?", orgID.String()).
Where("revoked_at IS NULL").
Where("expires_at > ?", time.Now().UTC()).
OrderExpr("created_at DESC").
Limit(1).
Scan(ctx)
if err != nil {
return nil, agentauthPgError(err)
}
return toAgentGrant(m)
}
func (s *PostgresStore) ListGrantsByUser(ctx context.Context, userID id.UserID) ([]*AgentGrant, error) {
var models []agentGrantModel
err := s.pg.NewSelect(&models).
Where("user_id = ?", userID.String()).
OrderExpr("created_at ASC").
Scan(ctx)
if err != nil {
return nil, agentauthPgError(err)
}
out := make([]*AgentGrant, 0, len(models))
for i := range models {
g, err := toAgentGrant(&models[i])
if err != nil {
return nil, err
}
out = append(out, g)
}
return out, nil
}
func (s *PostgresStore) UpdateAgentGrant(ctx context.Context, g *AgentGrant) error {
m, err := fromAgentGrant(g)
if err != nil {
return err
}
res, err := s.pg.NewUpdate(m).WherePK().Exec(ctx)
if err != nil {
return agentauthPgError(err)
}
rows, _ := res.RowsAffected() //nolint:errcheck // driver always supports RowsAffected
if rows == 0 {
return ErrNotFound
}
return nil
}
// StampLastUsed writes ONLY last_used_at and updated_at — never revoked_at,
// which RevokeAgentGrant owns exclusively. See the Store interface doc
// comment: a targeted UPDATE that never mentions revoked_at cannot resurrect
// a grant a concurrent revoke just set it on, the way a whole-row
// UpdateAgentGrant built from a stale read could.
func (s *PostgresStore) StampLastUsed(ctx context.Context, grantID id.AgentGrantID, t time.Time) error {
t = t.UTC()
res, err := s.pg.NewUpdate((*agentGrantModel)(nil)).
Set("last_used_at = ?", t).
Set("updated_at = ?", t).
Where("id = ?", grantID.String()).
Exec(ctx)
if err != nil {
return agentauthPgError(err)
}
rows, _ := res.RowsAffected() //nolint:errcheck // driver always supports RowsAffected
if rows == 0 {
return ErrNotFound
}
return nil
}
func (s *PostgresStore) RevokeAgentGrant(ctx context.Context, grantID id.AgentGrantID) error {
m := new(agentGrantModel)
err := s.pg.NewSelect(m).Where("id = ?", grantID.String()).Scan(ctx)
if err != nil {
return agentauthPgError(err)
}
if m.RevokedAt != nil {
// Already revoked: a no-op, not an error — matches MemoryStore.
return nil
}
now := time.Now().UTC()
_, err = s.pg.NewUpdate((*agentGrantModel)(nil)).
Set("revoked_at = ?", now).
Set("updated_at = ?", now).
Where("id = ?", grantID.String()).
Where("revoked_at IS NULL").
Exec(ctx)
return agentauthPgError(err)
}
func (s *PostgresStore) RevokeGrantsByUser(ctx context.Context, userID id.UserID) ([]id.AgentGrantID, error) {
return s.revokeGrantsWhere(ctx, "user_id = ?", []any{userID.String()})
}
func (s *PostgresStore) RevokeGrantsByUserOrg(ctx context.Context, userID id.UserID, orgID id.OrgID) ([]id.AgentGrantID, error) {
return s.revokeGrantsWhere(ctx, "user_id = ? AND org_id = ?", []any{userID.String(), orgID.String()})
}
func (s *PostgresStore) RevokeGrantsByOrg(ctx context.Context, orgID id.OrgID) ([]id.AgentGrantID, error) {
return s.revokeGrantsWhere(ctx, "org_id = ?", []any{orgID.String()})
}
// RevokeGrantsByAgent revokes the agent's grants. A nil orgID means "every
// org", not "the org whose id is empty" — the org filter is only applied
// when orgID carries a real value, matching MemoryStore.
func (s *PostgresStore) RevokeGrantsByAgent(ctx context.Context, agentID id.AgentID, orgID id.OrgID) ([]id.AgentGrantID, error) {
if orgID.IsNil() {
return s.revokeGrantsWhere(ctx, "agent_id = ?", []any{agentID.String()})
}
return s.revokeGrantsWhere(ctx, "agent_id = ? AND org_id = ?", []any{agentID.String(), orgID.String()})
}
// revokeGrantsWhere returns the ids of every grant matching the given
// filter — whether or not it was already revoked, per the Store interface
// contract documented on Store.RevokeGrantsByUser — and revokes any of them
// that weren't revoked already.
//
// The write runs BEFORE the read, not after: a select-then-update (the
// original shape here) leaves a window where a grant matching the filter,
// inserted between the two statements, gets caught and revoked by the
// UPDATE but was never in the SELECT's result — so its id is missing from
// the return value and sweepSessions never deletes its sessions, which is
// exactly the under-sweeping the interface comment warns against. Updating
// first closes that: any row this call revokes has revoked_at set before
// the SELECT ever runs, so "WHERE <filter> AND revoked_at IS NOT NULL"
// afterward is guaranteed to include it. A row that starts existing only
// after the UPDATE has run is, by construction, not one this call touched —
// it's still unrevoked, so the revoked_at IS NOT NULL filter correctly
// excludes it rather than falsely claiming it was swept.
func (s *PostgresStore) revokeGrantsWhere(ctx context.Context, where string, args []any) ([]id.AgentGrantID, error) {
now := time.Now().UTC()
upd := s.pg.NewUpdate((*agentGrantModel)(nil)).
Set("revoked_at = ?", now).
Set("updated_at = ?", now)
upd = upd.Where(where, args...)
upd = upd.Where("revoked_at IS NULL")
if _, err := upd.Exec(ctx); err != nil {
return nil, agentauthPgError(err)
}
var models []agentGrantModel
sel := s.pg.NewSelect(&models)
sel = sel.Where(where, args...)
sel = sel.Where("revoked_at IS NOT NULL")
if err := sel.Scan(ctx); err != nil {
return nil, agentauthPgError(err)
}
ids := make([]id.AgentGrantID, 0, len(models))
for i := range models {
gid, err := id.ParseAgentGrantID(models[i].ID)
if err != nil {
return nil, err
}
ids = append(ids, gid)
}
return ids, nil
}
// ──────────────────────────────────────────────────
// Org policy methods
// ──────────────────────────────────────────────────
func (s *PostgresStore) GetOrgPolicy(ctx context.Context, orgID id.OrgID) (*OrgAgentPolicy, error) {
m := new(orgPolicyModel)
err := s.pg.NewSelect(m).
Where("org_id = ?", orgID.String()).
Scan(ctx)
if err != nil {
return nil, agentauthPgError(err)
}
return toOrgPolicy(m)
}
func (s *PostgresStore) PutOrgPolicy(ctx context.Context, p *OrgAgentPolicy) error {
if err := validatePolicyMode(p.Mode); err != nil {
return err
}
m, err := fromOrgPolicy(p)
if err != nil {
return err
}
now := time.Now().UTC()
res, err := s.pg.NewUpdate(m).
Set("mode = ?", m.Mode).
Set("max_grant_ttl = ?", m.MaxGrantTTL).
Set("allowed_scopes = ?", m.AllowedScopes).
Set("updated_at = ?", now).
Where("org_id = ?", m.OrgID).
Exec(ctx)
if err != nil {
return agentauthPgError(err)
}
rows, _ := res.RowsAffected() //nolint:errcheck // driver always supports RowsAffected
if rows > 0 {
return nil
}
m.CreatedAt = now
m.UpdatedAt = now
_, err = s.pg.NewInsert(m).Exec(ctx)
return agentauthPgError(err)
}
// ──────────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────────
// agentauthPgError maps low-level pg failures to this package's sentinels.
// A unique-constraint violation on the agents.client_id index becomes
// ErrConflict — CreateAgent's atomicity requirement (the brief calls out
// that a check-then-insert races) is enforced by the partial unique index
// itself; this only translates the driver error the index produces.
func agentauthPgError(err error) error {
if err == nil {
return nil
}
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
msg := err.Error()
if strings.Contains(msg, "SQLSTATE 23505") || strings.Contains(msg, "duplicate key value") {
return ErrConflict
}
return err
}