feat(auth): add scoped JSON account and session queries for CLI clients
Build and publish container images / images (push) Successful in 18m18s
Build and publish container images / images (push) Successful in 18m18s
This commit is contained in:
1 parent
6f9752ea3a
commit
b650fe50d7
10 files changed
+640
No files matched your search
@@ -0,0 +1,123 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AuthSessionView deliberately contains no credential or credential hash.
|
||||
type AuthSessionView struct {
|
||||
UUID string `json:"uuid"`
|
||||
PrincipalUUID string `json:"principal_uuid"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AuthTimeMS int64 `json:"auth_time_ms"`
|
||||
LastSeenAtMS int64 `json:"last_seen_at_ms"`
|
||||
ExpiresAtMS int64 `json:"expires_at_ms"`
|
||||
RevokedAtMS int64 `json:"revoked_at_ms"`
|
||||
MFALevel int `json:"mfa_level"`
|
||||
Status string `json:"status"`
|
||||
IsCurrent bool `json:"is_current"`
|
||||
}
|
||||
|
||||
func (s *Store) CurrentAuthSession(ctx context.Context, domain, principal, token string) (AuthSessionView, error) {
|
||||
var v AuthSessionView
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT a.uuid,a.auth_time_ms,a.last_seen_at_ms,a.expires_at_ms,a.mfa_level
|
||||
FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid
|
||||
JOIN domain_memberships m ON m.domain_uuid=a.domain_uuid AND m.principal_uuid=p.uuid
|
||||
WHERE a.domain_uuid=`+s.sqlParam(1)+` AND a.principal_uuid=`+s.sqlParam(2)+` AND a.token_hash=`+s.sqlParam(3)+`
|
||||
AND a.revoked_at_ms=0 AND a.expires_at_ms>`+s.sqlParam(4)+` AND m.state='active' AND p.state IN ('active','readonly')`, domain, principal, hashAuthToken(token), time.Now().UnixMilli()).Scan(&v.UUID, &v.AuthTimeMS, &v.LastSeenAtMS, &v.ExpiresAtMS, &v.MFALevel)
|
||||
return v, s.sqlError("current auth session", err)
|
||||
}
|
||||
|
||||
// Callers must authorize domain-wide access before passing an empty principal.
|
||||
// LIMIT + 1 bounds both the response and the database result, not just JSON.
|
||||
func (s *Store) QueryAuthSessions(ctx context.Context, domain, principal, current string, history bool, limit int) ([]AuthSessionView, bool, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, false, ErrAccessDenied
|
||||
}
|
||||
args := []any{domain}
|
||||
where := `a.domain_uuid=` + s.sqlParam(1)
|
||||
if principal != "" {
|
||||
args = append(args, principal)
|
||||
where += ` AND a.principal_uuid=` + s.sqlParam(len(args))
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
if !history {
|
||||
args = append(args, now)
|
||||
where += ` AND a.revoked_at_ms=0 AND a.expires_at_ms>` + s.sqlParam(len(args))
|
||||
}
|
||||
args = append(args, limit+1)
|
||||
query := `SELECT a.uuid,a.principal_uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY i.subject,i.uuid LIMIT 1),p.uuid),p.display_name,a.auth_time_ms,a.last_seen_at_ms,a.expires_at_ms,a.revoked_at_ms,a.mfa_level
|
||||
FROM auth_sessions a JOIN principals p ON p.uuid=a.principal_uuid WHERE ` + where + ` ORDER BY a.auth_time_ms DESC,a.uuid DESC LIMIT ` + s.sqlParam(len(args))
|
||||
rows, err := s.DB.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, false, s.sqlError("query auth sessions", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]AuthSessionView, 0, limit+1)
|
||||
for rows.Next() {
|
||||
var v AuthSessionView
|
||||
if err = rows.Scan(&v.UUID, &v.PrincipalUUID, &v.Username, &v.DisplayName, &v.AuthTimeMS, &v.LastSeenAtMS, &v.ExpiresAtMS, &v.RevokedAtMS, &v.MFALevel); err != nil {
|
||||
return nil, false, s.sqlError("scan auth sessions", err)
|
||||
}
|
||||
v.Status = "active"
|
||||
if v.RevokedAtMS != 0 {
|
||||
v.Status = "revoked"
|
||||
} else if v.ExpiresAtMS <= now {
|
||||
v.Status = "expired"
|
||||
}
|
||||
v.IsCurrent = v.UUID == current
|
||||
out = append(out, v)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, false, s.sqlError("query auth sessions", err)
|
||||
}
|
||||
truncated := len(out) > limit
|
||||
if truncated {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, truncated, nil
|
||||
}
|
||||
|
||||
// Membership names, not a list of all groups visible to this principal.
|
||||
// Results are bounded and truncation is explicit for unusually large accounts.
|
||||
func (s *Store) AuthMembershipNames(ctx context.Context, domain, principal string) (roles, groups []string, truncated bool, err error) {
|
||||
roles, groups = make([]string, 0), make([]string, 0)
|
||||
queries := []string{
|
||||
`SELECT DISTINCT r.name FROM auth_roles r JOIN auth_role_bindings b ON b.role_uuid=r.uuid JOIN domain_memberships m ON m.uuid=b.membership_uuid WHERE r.domain_uuid=%s AND m.domain_uuid=r.domain_uuid AND m.principal_uuid=%s AND m.state='active' ORDER BY r.name LIMIT 101`,
|
||||
`SELECT DISTINCT g.name FROM ` + s.sqlGroupTable() + ` g JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid WHERE g.domain_uuid=%s AND m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' AND g.state='active' ORDER BY g.name LIMIT 101`,
|
||||
}
|
||||
for i, query := range queries {
|
||||
rows, e := s.DB.QueryContext(ctx, fmt.Sprintf(query, s.sqlParam(1), s.sqlParam(2)), domain, principal)
|
||||
if e != nil {
|
||||
return nil, nil, false, s.sqlError("auth memberships", e)
|
||||
}
|
||||
items := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if e = rows.Scan(&name); e != nil {
|
||||
break
|
||||
}
|
||||
items = append(items, name)
|
||||
}
|
||||
if e == nil {
|
||||
e = rows.Err()
|
||||
}
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return nil, nil, false, s.sqlError("auth memberships", e)
|
||||
}
|
||||
if len(items) > 100 {
|
||||
truncated = true
|
||||
items = items[:100]
|
||||
}
|
||||
if i == 0 {
|
||||
roles = items
|
||||
} else {
|
||||
groups = items
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAccountBackendAuthQueries(t *testing.T) {
|
||||
for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||
t.Run(fmt.Sprint(backend), func(t *testing.T) {
|
||||
s, d := accountBackendStore(t, backend)
|
||||
ctx := context.Background()
|
||||
p, err := s.BootstrapOwner(d, "owner", "synthetic auth query password", "Owner", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := s.CreateAuthSession(d, p.UUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, err := s.CurrentAuthSession(ctx, d, p.UUID, token)
|
||||
if err != nil || current.UUID == "" {
|
||||
t.Fatal(current, err)
|
||||
}
|
||||
for _, kind := range []string{"expired", "revoked"} {
|
||||
extra, e := s.CreateAuthSession(d, p.UUID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v, e := s.CurrentAuthSession(ctx, d, p.UUID, extra)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if kind == "expired" {
|
||||
_, e = s.DB.Exec(`UPDATE auth_sessions SET expires_at_ms=1 WHERE uuid=`+s.sqlParam(1), v.UUID)
|
||||
} else {
|
||||
e = s.RevokeAuthSession(extra)
|
||||
}
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
// A retained session in another domain must never appear in either scope.
|
||||
_, err = s.DB.Exec(`INSERT INTO auth_sessions(uuid,token_hash,principal_uuid,domain_uuid,auth_time_ms,expires_at_ms,last_seen_at_ms,mfa_level) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,1,`+s.sqlParam(5)+`,1,0)`, "foreign-session", "synthetic-foreign-hash", p.UUID, "foreign-domain", time.Now().Add(time.Hour).UnixMilli())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, principal := range []string{p.UUID, ""} {
|
||||
items, truncated, e := s.QueryAuthSessions(ctx, d, principal, current.UUID, false, 100)
|
||||
if e != nil || truncated || len(items) != 1 || !items[0].IsCurrent || items[0].Status != "active" {
|
||||
t.Fatal(items, truncated, e)
|
||||
}
|
||||
items, truncated, e = s.QueryAuthSessions(ctx, d, principal, current.UUID, true, 100)
|
||||
if e != nil || truncated || len(items) != 3 {
|
||||
t.Fatal(items, truncated, e)
|
||||
}
|
||||
statuses := map[string]int{}
|
||||
for _, v := range items {
|
||||
statuses[v.Status]++
|
||||
}
|
||||
if statuses["active"] != 1 || statuses["revoked"] != 1 || statuses["expired"] != 1 {
|
||||
t.Fatal(statuses)
|
||||
}
|
||||
items, truncated, e = s.QueryAuthSessions(ctx, d, principal, current.UUID, true, 1)
|
||||
if e != nil || !truncated || len(items) != 1 {
|
||||
t.Fatal(items, truncated, e)
|
||||
}
|
||||
}
|
||||
if _, e := s.CurrentAuthSession(ctx, "foreign-domain", p.UUID, token); e == nil {
|
||||
t.Fatal("cross-domain current session")
|
||||
}
|
||||
roles, groups, truncated, e := s.AuthMembershipNames(ctx, d, p.UUID)
|
||||
if e != nil || roles == nil || truncated || len(groups) < 2 {
|
||||
t.Fatal(roles, groups, truncated, e)
|
||||
}
|
||||
roles, groups, _, e = s.AuthMembershipNames(ctx, "foreign-domain", p.UUID)
|
||||
if e != nil || len(roles) != 0 || len(groups) != 0 {
|
||||
t.Fatal("cross-domain memberships", e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user