feat(identity): name, lifetime and last-used on personal API tokens

This commit is contained in:
sam committed 2026-10-27 15:37:44 +11:00
1 parent 3210e30ce4
commit 91be2114cf
23 files changed
+449 -99

No files matched your search

+110 -59
View File
@@ -28,6 +28,9 @@ type PersonalToken struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
CreatedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` // unset: never expires
LastUsedAt *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=last_used_at,json=lastUsedAt,proto3" json:"last_used_at,omitempty"` // unset: never used
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -76,9 +79,32 @@ func (x *PersonalToken) GetCreatedAt() *timestamppb.Timestamp {
return nil
}
func (x *PersonalToken) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *PersonalToken) GetExpiresAt() *timestamppb.Timestamp {
if x != nil {
return x.ExpiresAt
}
return nil
}
func (x *PersonalToken) GetLastUsedAt() *timestamppb.Timestamp {
if x != nil {
return x.LastUsedAt
}
return nil
}
type AddPersonalTokenRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` // unset: never expires
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -120,6 +146,20 @@ func (x *AddPersonalTokenRequest) GetId() string {
return ""
}
func (x *AddPersonalTokenRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AddPersonalTokenRequest) GetExpiresAt() *timestamppb.Timestamp {
if x != nil {
return x.ExpiresAt
}
return nil
}
type AddPersonalTokenResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -1936,13 +1976,21 @@ var File_state_v1_account_proto protoreflect.FileDescriptor
const file_state_v1_account_proto_rawDesc = "" +
"\n" +
"\x16state/v1/account.proto\x12\bstate.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x14state/v1/types.proto\"Z\n" +
"\x16state/v1/account.proto\x12\bstate.v1\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x14state/v1/types.proto\"\xe7\x01\n" +
"\rPersonalToken\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x129\n" +
"\n" +
"created_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\")\n" +
"created_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12\x12\n" +
"\x04name\x18\x03 \x01(\tR\x04name\x129\n" +
"\n" +
"expires_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x12<\n" +
"\flast_used_at\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\n" +
"lastUsedAt\"x\n" +
"\x17AddPersonalTokenRequest\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\"\x1a\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x129\n" +
"\n" +
"expires_at\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\"\x1a\n" +
"\x18AddPersonalTokenResponse\"\x1b\n" +
"\x19ListPersonalTokensRequest\"M\n" +
"\x1aListPersonalTokensResponse\x12/\n" +
@@ -2124,62 +2172,65 @@ var file_state_v1_account_proto_goTypes = []any{
}
var file_state_v1_account_proto_depIdxs = []int32{
41, // 0: state.v1.PersonalToken.created_at:type_name -> google.protobuf.Timestamp
0, // 1: state.v1.ListPersonalTokensResponse.tokens:type_name -> state.v1.PersonalToken
42, // 2: state.v1.RegisterAccountResponse.identity:type_name -> state.v1.Identity
42, // 3: state.v1.SignInAccountResponse.identity:type_name -> state.v1.Identity
41, // 4: state.v1.SignInAccountResponse.expires_at:type_name -> google.protobuf.Timestamp
42, // 5: state.v1.ResolveAccountSessionResponse.identity:type_name -> state.v1.Identity
19, // 6: state.v1.GetAuthenticationSettingsResponse.settings:type_name -> state.v1.AuthenticationSettings
19, // 7: state.v1.SaveAuthenticationSettingsRequest.settings:type_name -> state.v1.AuthenticationSettings
42, // 8: state.v1.FinishPasskeyResponse.identity:type_name -> state.v1.Identity
41, // 9: state.v1.FinishPasskeyResponse.expires_at:type_name -> google.protobuf.Timestamp
28, // 10: state.v1.ListPasskeysResponse.passkeys:type_name -> state.v1.Passkey
41, // 11: state.v1.OpenAccountSessionRequest.expires_at:type_name -> google.protobuf.Timestamp
42, // 12: state.v1.OpenAccountSessionResponse.identity:type_name -> state.v1.Identity
41, // 13: state.v1.OpenAccountSessionResponse.expires_at:type_name -> google.protobuf.Timestamp
20, // 14: state.v1.AccountService.GetAuthenticationSettings:input_type -> state.v1.GetAuthenticationSettingsRequest
22, // 15: state.v1.AccountService.SaveAuthenticationSettings:input_type -> state.v1.SaveAuthenticationSettingsRequest
24, // 16: state.v1.AccountService.BeginPasskey:input_type -> state.v1.BeginPasskeyRequest
26, // 17: state.v1.AccountService.FinishPasskey:input_type -> state.v1.FinishPasskeyRequest
29, // 18: state.v1.AccountService.ListPasskeys:input_type -> state.v1.ListPasskeysRequest
31, // 19: state.v1.AccountService.DeletePasskey:input_type -> state.v1.DeletePasskeyRequest
33, // 20: state.v1.AccountService.OpenAccountSession:input_type -> state.v1.OpenAccountSessionRequest
35, // 21: state.v1.AccountService.RequireFreshAccountSession:input_type -> state.v1.RequireFreshAccountSessionRequest
37, // 22: state.v1.AccountService.CreateAccountRecovery:input_type -> state.v1.CreateAccountRecoveryRequest
39, // 23: state.v1.AccountService.RecoverAccount:input_type -> state.v1.RecoverAccountRequest
7, // 24: state.v1.AccountService.AccountSetup:input_type -> state.v1.AccountSetupRequest
9, // 25: state.v1.AccountService.RegisterAccount:input_type -> state.v1.RegisterAccountRequest
11, // 26: state.v1.AccountService.SignInAccount:input_type -> state.v1.SignInAccountRequest
13, // 27: state.v1.AccountService.ResolveAccountSession:input_type -> state.v1.ResolveAccountSessionRequest
15, // 28: state.v1.AccountService.SignOutAccount:input_type -> state.v1.SignOutAccountRequest
17, // 29: state.v1.AccountService.ChangeAccountPassword:input_type -> state.v1.ChangeAccountPasswordRequest
1, // 30: state.v1.AccountService.AddPersonalToken:input_type -> state.v1.AddPersonalTokenRequest
3, // 31: state.v1.AccountService.ListPersonalTokens:input_type -> state.v1.ListPersonalTokensRequest
5, // 32: state.v1.AccountService.RevokePersonalToken:input_type -> state.v1.RevokePersonalTokenRequest
21, // 33: state.v1.AccountService.GetAuthenticationSettings:output_type -> state.v1.GetAuthenticationSettingsResponse
23, // 34: state.v1.AccountService.SaveAuthenticationSettings:output_type -> state.v1.SaveAuthenticationSettingsResponse
25, // 35: state.v1.AccountService.BeginPasskey:output_type -> state.v1.BeginPasskeyResponse
27, // 36: state.v1.AccountService.FinishPasskey:output_type -> state.v1.FinishPasskeyResponse
30, // 37: state.v1.AccountService.ListPasskeys:output_type -> state.v1.ListPasskeysResponse
32, // 38: state.v1.AccountService.DeletePasskey:output_type -> state.v1.DeletePasskeyResponse
34, // 39: state.v1.AccountService.OpenAccountSession:output_type -> state.v1.OpenAccountSessionResponse
36, // 40: state.v1.AccountService.RequireFreshAccountSession:output_type -> state.v1.RequireFreshAccountSessionResponse
38, // 41: state.v1.AccountService.CreateAccountRecovery:output_type -> state.v1.CreateAccountRecoveryResponse
40, // 42: state.v1.AccountService.RecoverAccount:output_type -> state.v1.RecoverAccountResponse
8, // 43: state.v1.AccountService.AccountSetup:output_type -> state.v1.AccountSetupResponse
10, // 44: state.v1.AccountService.RegisterAccount:output_type -> state.v1.RegisterAccountResponse
12, // 45: state.v1.AccountService.SignInAccount:output_type -> state.v1.SignInAccountResponse
14, // 46: state.v1.AccountService.ResolveAccountSession:output_type -> state.v1.ResolveAccountSessionResponse
16, // 47: state.v1.AccountService.SignOutAccount:output_type -> state.v1.SignOutAccountResponse
18, // 48: state.v1.AccountService.ChangeAccountPassword:output_type -> state.v1.ChangeAccountPasswordResponse
2, // 49: state.v1.AccountService.AddPersonalToken:output_type -> state.v1.AddPersonalTokenResponse
4, // 50: state.v1.AccountService.ListPersonalTokens:output_type -> state.v1.ListPersonalTokensResponse
6, // 51: state.v1.AccountService.RevokePersonalToken:output_type -> state.v1.RevokePersonalTokenResponse
33, // [33:52] is the sub-list for method output_type
14, // [14:33] is the sub-list for method input_type
14, // [14:14] is the sub-list for extension type_name
14, // [14:14] is the sub-list for extension extendee
0, // [0:14] is the sub-list for field type_name
41, // 1: state.v1.PersonalToken.expires_at:type_name -> google.protobuf.Timestamp
41, // 2: state.v1.PersonalToken.last_used_at:type_name -> google.protobuf.Timestamp
41, // 3: state.v1.AddPersonalTokenRequest.expires_at:type_name -> google.protobuf.Timestamp
0, // 4: state.v1.ListPersonalTokensResponse.tokens:type_name -> state.v1.PersonalToken
42, // 5: state.v1.RegisterAccountResponse.identity:type_name -> state.v1.Identity
42, // 6: state.v1.SignInAccountResponse.identity:type_name -> state.v1.Identity
41, // 7: state.v1.SignInAccountResponse.expires_at:type_name -> google.protobuf.Timestamp
42, // 8: state.v1.ResolveAccountSessionResponse.identity:type_name -> state.v1.Identity
19, // 9: state.v1.GetAuthenticationSettingsResponse.settings:type_name -> state.v1.AuthenticationSettings
19, // 10: state.v1.SaveAuthenticationSettingsRequest.settings:type_name -> state.v1.AuthenticationSettings
42, // 11: state.v1.FinishPasskeyResponse.identity:type_name -> state.v1.Identity
41, // 12: state.v1.FinishPasskeyResponse.expires_at:type_name -> google.protobuf.Timestamp
28, // 13: state.v1.ListPasskeysResponse.passkeys:type_name -> state.v1.Passkey
41, // 14: state.v1.OpenAccountSessionRequest.expires_at:type_name -> google.protobuf.Timestamp
42, // 15: state.v1.OpenAccountSessionResponse.identity:type_name -> state.v1.Identity
41, // 16: state.v1.OpenAccountSessionResponse.expires_at:type_name -> google.protobuf.Timestamp
20, // 17: state.v1.AccountService.GetAuthenticationSettings:input_type -> state.v1.GetAuthenticationSettingsRequest
22, // 18: state.v1.AccountService.SaveAuthenticationSettings:input_type -> state.v1.SaveAuthenticationSettingsRequest
24, // 19: state.v1.AccountService.BeginPasskey:input_type -> state.v1.BeginPasskeyRequest
26, // 20: state.v1.AccountService.FinishPasskey:input_type -> state.v1.FinishPasskeyRequest
29, // 21: state.v1.AccountService.ListPasskeys:input_type -> state.v1.ListPasskeysRequest
31, // 22: state.v1.AccountService.DeletePasskey:input_type -> state.v1.DeletePasskeyRequest
33, // 23: state.v1.AccountService.OpenAccountSession:input_type -> state.v1.OpenAccountSessionRequest
35, // 24: state.v1.AccountService.RequireFreshAccountSession:input_type -> state.v1.RequireFreshAccountSessionRequest
37, // 25: state.v1.AccountService.CreateAccountRecovery:input_type -> state.v1.CreateAccountRecoveryRequest
39, // 26: state.v1.AccountService.RecoverAccount:input_type -> state.v1.RecoverAccountRequest
7, // 27: state.v1.AccountService.AccountSetup:input_type -> state.v1.AccountSetupRequest
9, // 28: state.v1.AccountService.RegisterAccount:input_type -> state.v1.RegisterAccountRequest
11, // 29: state.v1.AccountService.SignInAccount:input_type -> state.v1.SignInAccountRequest
13, // 30: state.v1.AccountService.ResolveAccountSession:input_type -> state.v1.ResolveAccountSessionRequest
15, // 31: state.v1.AccountService.SignOutAccount:input_type -> state.v1.SignOutAccountRequest
17, // 32: state.v1.AccountService.ChangeAccountPassword:input_type -> state.v1.ChangeAccountPasswordRequest
1, // 33: state.v1.AccountService.AddPersonalToken:input_type -> state.v1.AddPersonalTokenRequest
3, // 34: state.v1.AccountService.ListPersonalTokens:input_type -> state.v1.ListPersonalTokensRequest
5, // 35: state.v1.AccountService.RevokePersonalToken:input_type -> state.v1.RevokePersonalTokenRequest
21, // 36: state.v1.AccountService.GetAuthenticationSettings:output_type -> state.v1.GetAuthenticationSettingsResponse
23, // 37: state.v1.AccountService.SaveAuthenticationSettings:output_type -> state.v1.SaveAuthenticationSettingsResponse
25, // 38: state.v1.AccountService.BeginPasskey:output_type -> state.v1.BeginPasskeyResponse
27, // 39: state.v1.AccountService.FinishPasskey:output_type -> state.v1.FinishPasskeyResponse
30, // 40: state.v1.AccountService.ListPasskeys:output_type -> state.v1.ListPasskeysResponse
32, // 41: state.v1.AccountService.DeletePasskey:output_type -> state.v1.DeletePasskeyResponse
34, // 42: state.v1.AccountService.OpenAccountSession:output_type -> state.v1.OpenAccountSessionResponse
36, // 43: state.v1.AccountService.RequireFreshAccountSession:output_type -> state.v1.RequireFreshAccountSessionResponse
38, // 44: state.v1.AccountService.CreateAccountRecovery:output_type -> state.v1.CreateAccountRecoveryResponse
40, // 45: state.v1.AccountService.RecoverAccount:output_type -> state.v1.RecoverAccountResponse
8, // 46: state.v1.AccountService.AccountSetup:output_type -> state.v1.AccountSetupResponse
10, // 47: state.v1.AccountService.RegisterAccount:output_type -> state.v1.RegisterAccountResponse
12, // 48: state.v1.AccountService.SignInAccount:output_type -> state.v1.SignInAccountResponse
14, // 49: state.v1.AccountService.ResolveAccountSession:output_type -> state.v1.ResolveAccountSessionResponse
16, // 50: state.v1.AccountService.SignOutAccount:output_type -> state.v1.SignOutAccountResponse
18, // 51: state.v1.AccountService.ChangeAccountPassword:output_type -> state.v1.ChangeAccountPasswordResponse
2, // 52: state.v1.AccountService.AddPersonalToken:output_type -> state.v1.AddPersonalTokenResponse
4, // 53: state.v1.AccountService.ListPersonalTokens:output_type -> state.v1.ListPersonalTokensResponse
6, // 54: state.v1.AccountService.RevokePersonalToken:output_type -> state.v1.RevokePersonalTokenResponse
36, // [36:55] is the sub-list for method output_type
17, // [17:36] is the sub-list for method input_type
17, // [17:17] is the sub-list for extension type_name
17, // [17:17] is the sub-list for extension extendee
0, // [0:17] is the sub-list for field type_name
}
func init() { file_state_v1_account_proto_init() }
+31 -5
View File
@@ -37,23 +37,49 @@ func PersonalTokenSubject(raw string) (Subject, bool) {
}
// PersonalToken is one token as its owner sees it: the subject it binds as,
// which identifies it without revealing it, and when it was made.
// which identifies it without revealing it, its name, and its lifetime. A nil
// ExpiresAt never lapses; a nil LastUsedAt has never authenticated.
type PersonalToken struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at"`
LastUsedAt *time.Time `json:"last_used_at"`
}
// lastUsedGranularity bounds how often authentication writes a token's last use.
const lastUsedGranularity = time.Minute
// PersonalTokenStore is the store side of personal tokens, for one identity.
type PersonalTokenStore interface {
BindSubject(context.Context, IdentityID, Subject, Audit) error
BindPersonalToken(ctx context.Context, id IdentityID, subject Subject, name string, expiresAt *time.Time, audit Audit) error
SubjectsOf(ctx context.Context, id IdentityID, issuer string) ([]PersonalToken, error)
UnbindSubject(context.Context, IdentityID, Subject, Audit) error
PersonalTokenOf(context.Context, Subject) (PersonalToken, error)
TouchPersonalToken(context.Context, Subject, time.Time) error
}
// UsePersonalToken admits a presented token: an expired token is ErrNotFound,
// exactly as an unknown one, and a successful use is recorded at most once a
// minute.
func UsePersonalToken(ctx context.Context, store PersonalTokenStore, subject Subject, now time.Time) error {
token, err := store.PersonalTokenOf(ctx, subject)
if err != nil {
return err
}
if token.ExpiresAt != nil && !now.Before(*token.ExpiresAt) {
return ErrNotFound
}
if token.LastUsedAt == nil || now.Sub(*token.LastUsedAt) >= lastUsedGranularity {
return store.TouchPersonalToken(ctx, subject, now)
}
return nil
}
// PersonalTokens is personal tokens as a remote caller sees them: the State
// Store acts on the caller's own principal, so no method names an identity.
type PersonalTokens interface {
AddPersonalToken(ctx context.Context, subject Subject) error
AddPersonalToken(ctx context.Context, subject Subject, name string, expiresAt *time.Time) error
ListPersonalTokens(ctx context.Context) ([]PersonalToken, error)
RevokePersonalToken(ctx context.Context, id string) error
}
+52
View File
@@ -0,0 +1,52 @@
package identity
import (
"context"
"errors"
"testing"
"time"
)
type tokenFake struct {
PersonalTokenStore
token PersonalToken
touched int
}
func (f *tokenFake) PersonalTokenOf(context.Context, Subject) (PersonalToken, error) {
return f.token, nil
}
func (f *tokenFake) TouchPersonalToken(context.Context, Subject, time.Time) error {
f.touched++
return nil
}
// TestUsePersonalToken pins that an expired token is refused and that last use
// is written at most once a minute.
func TestUsePersonalToken(t *testing.T) {
now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC)
at := func(d time.Duration) *time.Time { v := now.Add(d); return &v }
tests := []struct {
name string
token PersonalToken
wantErr error
wantTouched int
}{
{"valid", PersonalToken{ExpiresAt: at(time.Hour)}, nil, 1},
{"expired", PersonalToken{ExpiresAt: at(-time.Second)}, ErrNotFound, 0},
{"expires now", PersonalToken{ExpiresAt: at(0)}, ErrNotFound, 0},
{"no expiry", PersonalToken{}, nil, 1},
{"used seconds ago", PersonalToken{LastUsedAt: at(-10 * time.Second)}, nil, 0},
{"used minutes ago", PersonalToken{LastUsedAt: at(-2 * time.Minute)}, nil, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &tokenFake{token: tt.token}
err := UsePersonalToken(context.Background(), f, Subject{}, now)
if !errors.Is(err, tt.wantErr) || f.touched != tt.wantTouched {
t.Fatalf("err %v touched %d, want %v and %d", err, f.touched, tt.wantErr, tt.wantTouched)
}
})
}
}
+50 -1
View File
@@ -310,6 +310,16 @@ func (s *Store) ClaimSubject(ctx context.Context, placeholder, subject identity.
// BindSubject binds an identity to the provider subject that asserts it,
// moving any prior binding for that subject.
func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
return s.bindSubject(ctx, id, subject, "", nil, audit)
}
// BindPersonalToken binds a personal token's subject with the name and expiry
// its owner chose; a nil expiry never lapses.
func (s *Store) BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error {
return s.bindSubject(ctx, id, subject, name, expiresAt, audit)
}
func (s *Store) bindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error {
if err := subject.Validate(); err != nil {
return err
}
@@ -339,6 +349,7 @@ func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject
if err := q.UpsertIdentitySubject(ctx, postgresdb.UpsertIdentitySubjectParams{
Issuer: subject.Issuer, Subject: subject.Subject, IdentityID: string(id), BoundAt: now,
Name: name, ExpiresAt: timestamptzOf(expiresAt),
}); err != nil {
return err
}
@@ -360,11 +371,34 @@ func (s *Store) SubjectsOf(ctx context.Context, id identity.IdentityID, issuer s
}
out := make([]identity.PersonalToken, 0, len(rows))
for _, row := range rows {
out = append(out, identity.PersonalToken{ID: row.Subject, CreatedAt: row.BoundAt})
out = append(out, identity.PersonalToken{
ID: row.Subject, Name: row.Name, CreatedAt: row.BoundAt, ExpiresAt: timePtr(row.ExpiresAt), LastUsedAt: timePtr(row.LastUsedAt),
})
}
return out, nil
}
// PersonalTokenOf returns one token's lifetime and last use, whoever owns it.
func (s *Store) PersonalTokenOf(ctx context.Context, subject identity.Subject) (identity.PersonalToken, error) {
row, err := postgresdb.New(s.pool).GetIdentitySubjectUse(ctx, postgresdb.GetIdentitySubjectUseParams{Issuer: subject.Issuer, Subject: subject.Subject})
if errors.Is(err, pgx.ErrNoRows) {
return identity.PersonalToken{}, identity.ErrNotFound
}
if err != nil {
return identity.PersonalToken{}, err
}
return identity.PersonalToken{
ID: row.Subject, Name: row.Name, CreatedAt: row.BoundAt, ExpiresAt: timePtr(row.ExpiresAt), LastUsedAt: timePtr(row.LastUsedAt),
}, nil
}
// TouchPersonalToken records when a token last authenticated.
func (s *Store) TouchPersonalToken(ctx context.Context, subject identity.Subject, at time.Time) error {
return postgresdb.New(s.pool).TouchIdentitySubject(ctx, postgresdb.TouchIdentitySubjectParams{
Issuer: subject.Issuer, Subject: subject.Subject, LastUsedAt: timestamptzOf(&at),
})
}
// UnbindSubject removes one of an identity's bindings; a binding the
// identity does not hold is ErrNotFound, so no caller can remove another's.
func (s *Store) UnbindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
@@ -435,3 +469,18 @@ func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) e
}
return nil
}
func timestamptzOf(t *time.Time) pgtype.Timestamptz {
if t == nil {
return pgtype.Timestamptz{}
}
return pgtype.Timestamptz{Time: *t, Valid: true}
}
func timePtr(t pgtype.Timestamptz) *time.Time {
if !t.Valid {
return nil
}
v := t.Time
return &v
}
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE identity_subjects
ADD COLUMN name text NOT NULL DEFAULT '',
ADD COLUMN expires_at timestamptz,
ADD COLUMN last_used_at timestamptz;
-- +goose Down
ALTER TABLE identity_subjects
DROP COLUMN last_used_at,
DROP COLUMN expires_at,
DROP COLUMN name;
@@ -77,6 +77,37 @@ func (q *Queries) GetIdentity(ctx context.Context, id string) (Identity, error)
return i, err
}
const getIdentitySubjectUse = `-- name: GetIdentitySubjectUse :one
SELECT subject, bound_at, name, expires_at, last_used_at FROM identity_subjects
WHERE issuer = $1 AND subject = $2
`
type GetIdentitySubjectUseParams struct {
Issuer string
Subject string
}
type GetIdentitySubjectUseRow struct {
Subject string
BoundAt time.Time
Name string
ExpiresAt pgtype.Timestamptz
LastUsedAt pgtype.Timestamptz
}
func (q *Queries) GetIdentitySubjectUse(ctx context.Context, arg GetIdentitySubjectUseParams) (GetIdentitySubjectUseRow, error) {
row := q.db.QueryRow(ctx, getIdentitySubjectUse, arg.Issuer, arg.Subject)
var i GetIdentitySubjectUseRow
err := row.Scan(
&i.Subject,
&i.BoundAt,
&i.Name,
&i.ExpiresAt,
&i.LastUsedAt,
)
return i, err
}
const getVisibleIdentity = `-- name: GetVisibleIdentity :one
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities WHERE id = $1 AND ($2::text IS NULL
@@ -259,7 +290,7 @@ func (q *Queries) ListIdentities(ctx context.Context, scopeOrg pgtype.Text) ([]I
}
const listIdentitySubjects = `-- name: ListIdentitySubjects :many
SELECT subject, bound_at FROM identity_subjects
SELECT subject, bound_at, name, expires_at, last_used_at FROM identity_subjects
WHERE identity_id = $1 AND issuer = $2
ORDER BY bound_at DESC
`
@@ -270,8 +301,11 @@ type ListIdentitySubjectsParams struct {
}
type ListIdentitySubjectsRow struct {
Subject string
BoundAt time.Time
Subject string
BoundAt time.Time
Name string
ExpiresAt pgtype.Timestamptz
LastUsedAt pgtype.Timestamptz
}
func (q *Queries) ListIdentitySubjects(ctx context.Context, arg ListIdentitySubjectsParams) ([]ListIdentitySubjectsRow, error) {
@@ -283,7 +317,13 @@ func (q *Queries) ListIdentitySubjects(ctx context.Context, arg ListIdentitySubj
var items []ListIdentitySubjectsRow
for rows.Next() {
var i ListIdentitySubjectsRow
if err := rows.Scan(&i.Subject, &i.BoundAt); err != nil {
if err := rows.Scan(
&i.Subject,
&i.BoundAt,
&i.Name,
&i.ExpiresAt,
&i.LastUsedAt,
); err != nil {
return nil, err
}
items = append(items, i)
@@ -348,6 +388,21 @@ func (q *Queries) ResolveIdentitySubject(ctx context.Context, arg ResolveIdentit
return i, err
}
const touchIdentitySubject = `-- name: TouchIdentitySubject :exec
UPDATE identity_subjects SET last_used_at = $3 WHERE issuer = $1 AND subject = $2
`
type TouchIdentitySubjectParams struct {
Issuer string
Subject string
LastUsedAt pgtype.Timestamptz
}
func (q *Queries) TouchIdentitySubject(ctx context.Context, arg TouchIdentitySubjectParams) error {
_, err := q.db.Exec(ctx, touchIdentitySubject, arg.Issuer, arg.Subject, arg.LastUsedAt)
return err
}
const updateIdentity = `-- name: UpdateIdentity :execrows
UPDATE identities SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5
WHERE id = $1 AND version = $6
@@ -392,9 +447,10 @@ func (q *Queries) UpdateTaskIdentity(ctx context.Context, arg UpdateTaskIdentity
}
const upsertIdentitySubject = `-- name: UpsertIdentitySubject :exec
INSERT INTO identity_subjects (issuer, subject, identity_id, bound_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT (issuer, subject) DO UPDATE SET identity_id = excluded.identity_id, bound_at = excluded.bound_at
INSERT INTO identity_subjects (issuer, subject, identity_id, bound_at, name, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (issuer, subject) DO UPDATE SET identity_id = excluded.identity_id, bound_at = excluded.bound_at,
name = excluded.name, expires_at = excluded.expires_at
`
type UpsertIdentitySubjectParams struct {
@@ -402,6 +458,8 @@ type UpsertIdentitySubjectParams struct {
Subject string
IdentityID string
BoundAt time.Time
Name string
ExpiresAt pgtype.Timestamptz
}
func (q *Queries) UpsertIdentitySubject(ctx context.Context, arg UpsertIdentitySubjectParams) error {
@@ -410,6 +468,8 @@ func (q *Queries) UpsertIdentitySubject(ctx context.Context, arg UpsertIdentityS
arg.Subject,
arg.IdentityID,
arg.BoundAt,
arg.Name,
arg.ExpiresAt,
)
return err
}
@@ -266,6 +266,9 @@ type IdentitySubject struct {
Subject string
IdentityID string
BoundAt time.Time
Name string
ExpiresAt pgtype.Timestamptz
LastUsedAt pgtype.Timestamptz
}
type InstalledPackage struct {
@@ -73,17 +73,25 @@ WHERE issuer = @issuer AND subject = @placeholder
RETURNING identity_id;
-- name: UpsertIdentitySubject :exec
INSERT INTO identity_subjects (issuer, subject, identity_id, bound_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT (issuer, subject) DO UPDATE SET identity_id = excluded.identity_id, bound_at = excluded.bound_at;
INSERT INTO identity_subjects (issuer, subject, identity_id, bound_at, name, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (issuer, subject) DO UPDATE SET identity_id = excluded.identity_id, bound_at = excluded.bound_at,
name = excluded.name, expires_at = excluded.expires_at;
-- name: UpdateTaskIdentity :exec
UPDATE tasks SET identity = $1 WHERE identity = $2;
-- name: ListIdentitySubjects :many
SELECT subject, bound_at FROM identity_subjects
SELECT subject, bound_at, name, expires_at, last_used_at FROM identity_subjects
WHERE identity_id = $1 AND issuer = $2
ORDER BY bound_at DESC;
-- name: GetIdentitySubjectUse :one
SELECT subject, bound_at, name, expires_at, last_used_at FROM identity_subjects
WHERE issuer = $1 AND subject = $2;
-- name: TouchIdentitySubject :exec
UPDATE identity_subjects SET last_used_at = $3 WHERE issuer = $1 AND subject = $2;
-- name: DeleteIdentitySubject :execrows
DELETE FROM identity_subjects WHERE identity_id = $1 AND issuer = $2 AND subject = $3;
@@ -3,6 +3,7 @@ package staterpc
import (
"context"
"errors"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -74,7 +75,13 @@ func (s *identityServer) ResolveIdentitySubject(ctx context.Context, request *pb
if s.deps.SubjectBindings == nil {
return nil, status.Error(codes.Unavailable, "identity subject bindings unavailable")
}
value, err := s.deps.SubjectBindings.ResolveSubject(ctx, identity.Subject{Issuer: request.Issuer, Subject: request.Subject})
subject := identity.Subject{Issuer: request.Issuer, Subject: request.Subject}
if subject.Issuer == identity.PersonalTokenIssuer && s.deps.PersonalTokens != nil {
if err := identity.UsePersonalToken(ctx, s.deps.PersonalTokens, subject, time.Now()); err != nil {
return nil, identityStatus(err)
}
}
value, err := s.deps.SubjectBindings.ResolveSubject(ctx, subject)
if err != nil {
return nil, identityStatus(err)
}
@@ -4,9 +4,11 @@ import (
"context"
"encoding/hex"
"fmt"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
@@ -47,7 +49,7 @@ func (s *accountServer) AddPersonalToken(ctx context.Context, r *pb.AddPersonalT
if err != nil {
return nil, err
}
if err := s.deps.PersonalTokens.BindSubject(ctx, owner, subject, tokenAudit(ctx, owner, r.GetId())); err != nil {
if err := s.deps.PersonalTokens.BindPersonalToken(ctx, owner, subject, r.GetName(), optionalTime(r.GetExpiresAt()), tokenAudit(ctx, owner, r.GetId())); err != nil {
return nil, identityStatus(err)
}
return &pb.AddPersonalTokenResponse{}, nil
@@ -64,7 +66,10 @@ func (s *accountServer) ListPersonalTokens(ctx context.Context, _ *pb.ListPerson
}
out := make([]*pb.PersonalToken, 0, len(tokens))
for _, t := range tokens {
out = append(out, &pb.PersonalToken{Id: t.ID, CreatedAt: timestamp(t.CreatedAt)})
out = append(out, &pb.PersonalToken{
Id: t.ID, Name: t.Name, CreatedAt: timestamp(t.CreatedAt),
ExpiresAt: optionalTimestamp(t.ExpiresAt), LastUsedAt: optionalTimestamp(t.LastUsedAt),
})
}
return &pb.ListPersonalTokensResponse{Tokens: out}, nil
}
@@ -84,8 +89,8 @@ func (s *accountServer) RevokePersonalToken(ctx context.Context, r *pb.RevokePer
return &pb.RevokePersonalTokenResponse{}, nil
}
func (c *Client) AddPersonalToken(ctx context.Context, subject identity.Subject) error {
_, err := c.account.AddPersonalToken(ctx, &pb.AddPersonalTokenRequest{Id: subject.Subject})
func (c *Client) AddPersonalToken(ctx context.Context, subject identity.Subject, name string, expiresAt *time.Time) error {
_, err := c.account.AddPersonalToken(ctx, &pb.AddPersonalTokenRequest{Id: subject.Subject, Name: name, ExpiresAt: optionalTimestamp(expiresAt)})
return identityClientError(err)
}
@@ -96,7 +101,10 @@ func (c *Client) ListPersonalTokens(ctx context.Context) ([]identity.PersonalTok
}
out := make([]identity.PersonalToken, 0, len(r.GetTokens()))
for _, t := range r.GetTokens() {
out = append(out, identity.PersonalToken{ID: t.GetId(), CreatedAt: timeValue(t.GetCreatedAt())})
out = append(out, identity.PersonalToken{
ID: t.GetId(), Name: t.GetName(), CreatedAt: timeValue(t.GetCreatedAt()),
ExpiresAt: optionalTime(t.GetExpiresAt()), LastUsedAt: optionalTime(t.GetLastUsedAt()),
})
}
return out, nil
}
@@ -105,3 +113,18 @@ func (c *Client) RevokePersonalToken(ctx context.Context, id string) error {
_, err := c.account.RevokePersonalToken(ctx, &pb.RevokePersonalTokenRequest{Id: id})
return identityClientError(err)
}
func optionalTimestamp(t *time.Time) *timestamppb.Timestamp {
if t == nil {
return nil
}
return timestamppb.New(*t)
}
func optionalTime(t *timestamppb.Timestamp) *time.Time {
if t == nil {
return nil
}
v := t.AsTime()
return &v
}
@@ -4,6 +4,7 @@ import (
"context"
"strings"
"testing"
"time"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
@@ -15,7 +16,7 @@ type tokenCalls struct {
owner identity.IdentityID
}
func (t *tokenCalls) BindSubject(_ context.Context, id identity.IdentityID, _ identity.Subject, _ identity.Audit) error {
func (t *tokenCalls) BindPersonalToken(_ context.Context, id identity.IdentityID, _ identity.Subject, _ string, _ *time.Time, _ identity.Audit) error {
t.owner = id
return nil
}
+30 -1
View File
@@ -1,12 +1,18 @@
package webui
import (
"encoding/json"
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
const maxTokenNameLength = 40
// Personal API tokens belong to the signed-in person; the State Store acts
// on the principal the request carries, so these handlers name no one.
@@ -35,12 +41,35 @@ func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Reques
if !s.personalTokensReady(w, r) {
return
}
var body struct {
Name string `json:"name"`
Days int `json:"days"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
name := strings.TrimSpace(body.Name)
if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength {
http.Error(w, "Name a token in up to 40 characters.", http.StatusBadRequest)
return
}
var expiresAt *time.Time
switch body.Days {
case 0:
case 7, 30, 90:
t := time.Now().UTC().AddDate(0, 0, body.Days)
expiresAt = &t
default:
http.Error(w, "Lifetime is 7, 30 or 90 days, or none.", http.StatusBadRequest)
return
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
if err := s.PersonalTokens.AddPersonalToken(r.Context(), subject); err != nil {
if err := s.PersonalTokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
writeIdentityError(w, err)
return
}
+3 -2
View File
@@ -6,6 +6,7 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
@@ -65,7 +66,7 @@ type recordingTokens struct{ owner identity.IdentityID }
// AddPersonalToken mirrors the State Store's rule: only a signed-in person's
// principal may own a personal token.
func (t *recordingTokens) AddPersonalToken(ctx context.Context, _ identity.Subject) error {
func (t *recordingTokens) AddPersonalToken(ctx context.Context, _ identity.Subject, _ string, _ *time.Time) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok || p.IdentityID == identity.SystemID || p.Role("") != org.RoleOwner {
return identity.ErrInvalid
@@ -120,7 +121,7 @@ func TestSharedTokenOperatorPostsPersonalToken(t *testing.T) {
}
handler := s.requireToken(s.authorize(http.HandlerFunc(s.handlePersonalTokenCreate)))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", nil)
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", strings.NewReader(`{"name":"ci","days":30}`))
req.Header.Set("Authorization", "Bearer shared")
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {