oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package dashboard
2
3import (
4 "context"
5 "crypto/sha256"
6 "database/sql"
7 "embed"
8 "time"
9)
10
11// Migrations contain only replay digests and clock bounds, never pulled content.
12//
13//go:embed migrations/*.sql
14var Migrations embed.FS
15
16// Consume commits replay use before an app resolves identity or reads content.
17// The clock watermark survives restart and rejects backward movement beyond 30s.
18func Consume(ctx context.Context, db *sql.DB, c Claims, now time.Time) error {
19 tx, e := db.BeginTx(ctx, nil)
20 if e != nil {
21 return ErrUnavailable
22 }
23 defer tx.Rollback()
24 var observed int64
25 if e = tx.QueryRowContext(ctx, `UPDATE oficina_dashboard_clock SET observed=MAX(observed,?) WHERE id=1 RETURNING observed`, now.Unix()).Scan(&observed); e != nil {
26 return ErrUnavailable
27 }
28 if now.Unix() < observed-30 || c.Expires <= now.Unix() {
29 return ErrRefused
30 }
31 if _, e = tx.ExecContext(ctx, `DELETE FROM oficina_dashboard_replay WHERE expires < ?`, now.Unix()-30); e != nil {
32 return ErrUnavailable
33 }
34 var count int
35 if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM oficina_dashboard_replay`).Scan(&count); e != nil || count >= 10000 {
36 return ErrUnavailable
37 }
38 h := sha256.Sum256([]byte(c.Issuer + "\x00" + c.ID))
39 res, e := tx.ExecContext(ctx, `INSERT INTO oficina_dashboard_replay(digest,expires) VALUES(?,?) ON CONFLICT(digest) DO NOTHING`, h[:], c.Expires)
40 if e != nil {
41 return ErrUnavailable
42 }
43 n, e := res.RowsAffected()
44 if e != nil || n != 1 {
45 return ErrRefused
46 }
47 if tx.Commit() != nil {
48 return ErrUnavailable
49 }
50 return nil
51}
52