mirror of
https://github.com/hanzoai/ca.git
synced 2026-11-03 18:08:27 +00:00
* Fix issues F-003, 006, 001, 022
* Fix issues F-025, 026, 010, 008
- Login tokens name their identity provider in the `provider` claim;
SelectOrg and GetUserToken read it with pb.IDPFromString, which also
takes the number older tokens carry, and AuthenticateAPIKey answers
Provider Undefined.
- A login that fails after the callback decodes its state lands on the
redirect URI of the client, in its response mode, with `error` and
`error_description` (RFC 6749 section 4.1.2.1); a server-side failure
is described by its status text only. The calls to an IdP take the
request context and a client with a timeout, and the answer of the IdP
stays in the server log.
- The platform bootstrap reads its ca-config with ca.LoadBootstrapConfig,
which refuses an issuer URL template with `${ISSUER_ID}` or
`$ISSUER_ID`: the loader expands them to an empty string. The proto,
README and CLI help name `:ISSUER_ID`.
- CaDb.RegisterIssuer takes the trust anchor of a root issuer and writes
both in one transaction; the backend service and the bootstrap pass it,
and an anchor registered in another scope is AlreadyExists.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Address PR review comments
- Invite acceptance deletes the invite in its transaction
(query.TakeInvite, DELETE ... RETURNING) and grants from the deleted
row: a withdrawn or already accepted invite grants nothing, a re-issued
one grants its current role, and an email mismatch, an expired invite or
a failed grant rolls the delete back.
- CaDb.RegisterIssuer requires the anchor of a root issuer and refuses one
for any other issuer; the service always builds it for a root.
- The OAuth response is merged into the query of a redirect URI that has
one, and replaces its fragment in fragment mode.
- The codemap describes the transactions of RegisterOrg and the invite
acceptance.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
245 lines
7.2 KiB
Go
245 lines
7.2 KiB
Go
package pgsql
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/cockroachdb/errors"
|
|
"github.com/effective-security/trustyca/internal/db/model"
|
|
"github.com/effective-security/trustyca/internal/db/pgsql/query"
|
|
"github.com/effective-security/trustyca/internal/db/schema"
|
|
"github.com/effective-security/xdb"
|
|
"github.com/effective-security/xlog"
|
|
)
|
|
|
|
// DefaultInviteExpiry is the validity of an invite when the caller does not
|
|
// set ExpiresAt
|
|
const DefaultInviteExpiry = 14 * 24 * time.Hour
|
|
|
|
// CreateInvite creates or updates an invite for a user to join an org
|
|
// (empty ProjectID) or a project
|
|
func (p *Provider) CreateInvite(ctx context.Context, invite *model.Invite) (*model.Invite, error) {
|
|
id := invite.ID
|
|
if id.UInt64() == 0 {
|
|
id = p.NextID()
|
|
}
|
|
|
|
inv := *invite
|
|
inv.Email = strings.ToLower(inv.Email)
|
|
if inv.ExpiresAt.IsZero() {
|
|
inv.ExpiresAt = xdb.Time(time.Now().Add(DefaultInviteExpiry))
|
|
}
|
|
|
|
err := xdb.Validate(&inv)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
q, name := query.CreateInvite()
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
res, err := xdb.QueryRow[model.Invite](ctx, p,
|
|
q,
|
|
id.UInt64(),
|
|
inv.OrgID,
|
|
inv.ProjectID,
|
|
inv.InviterID,
|
|
inv.Email,
|
|
inv.Role,
|
|
inv.ExpiresAt,
|
|
)
|
|
if err != nil {
|
|
p.CheckErrIDConflict(ctx, err, id.UInt64())
|
|
return nil, err
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// GetInvite returns an invite by ID
|
|
func (p *Provider) GetInvite(ctx context.Context, id uint64) (*model.Invite, error) {
|
|
q, name := query.GetRowByID(&schema.InviteTableInfo)
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
res, err := xdb.QueryRow[model.Invite](ctx, p, q, id)
|
|
if err != nil {
|
|
return nil, xdb.CheckNotFoundError(err, schema.InviteTableInfo.Name, id)
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// GetInviteByOrgAndEmail returns an invite by org, scope and email.
|
|
// projectID 0 returns the Org scope invite.
|
|
func (p *Provider) GetInviteByOrgAndEmail(ctx context.Context, orgID, projectID uint64, email string) (*model.Invite, error) {
|
|
req := &query.GetInviteRequest{
|
|
OrgID: orgID,
|
|
ProjectID: projectID,
|
|
Email: strings.ToLower(email),
|
|
}
|
|
qp := req.QueryParams()
|
|
q, name := query.GetInvite(qp)
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
res, err := xdb.QueryRow[model.Invite](ctx, p, q, qp.Args()...)
|
|
if err != nil {
|
|
return nil, xdb.CheckNotFoundError(err, schema.InviteTableInfo.Name, fmt.Sprintf("%d/%d/%s", orgID, projectID, req.Email))
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// GetOrgInvites returns invites of all scopes for an org
|
|
func (p *Provider) GetOrgInvites(ctx context.Context, orgID uint64) (model.InviteSlice, error) {
|
|
q, name := query.GetOrgInvites()
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
var rs model.InviteResult
|
|
err := xdb.ExecuteQuery(ctx, p.DB(), &rs, q, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return rs.Rows, nil
|
|
}
|
|
|
|
// GetUserInvites returns invites for a user's email
|
|
func (p *Provider) GetUserInvites(ctx context.Context, email string) (model.InviteSlice, error) {
|
|
q, name := query.GetUserInvites()
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
email = strings.ToLower(email)
|
|
var rs model.InviteResult
|
|
err := xdb.ExecuteQuery(ctx, p.DB(), &rs, q, email)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return rs.Rows, nil
|
|
}
|
|
|
|
// DeleteInviteByID deletes an invite by ID
|
|
func (p *Provider) DeleteInviteByID(ctx context.Context, id uint64) (int64, error) {
|
|
q, name := query.DeleteRowByID(&schema.InviteTableInfo)
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
res, err := p.ExecContext(ctx, q, id)
|
|
if err != nil {
|
|
return 0, errors.WithStack(err)
|
|
}
|
|
return res.RowsAffected()
|
|
}
|
|
|
|
// DeleteInvite deletes invites at the requested scope
|
|
func (p *Provider) DeleteInvite(ctx context.Context, r *query.DeleteInviteRequest) (int64, error) {
|
|
if r.OrgID == 0 && r.Email == "" {
|
|
return 0, errors.New("orgID or email is required")
|
|
}
|
|
req := *r
|
|
req.Email = strings.ToLower(req.Email)
|
|
qp := req.QueryParams()
|
|
q, name := query.DeleteInvite(qp)
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
res, err := p.ExecContext(ctx, q, qp.Args()...)
|
|
if err != nil {
|
|
return 0, errors.WithStack(err)
|
|
}
|
|
return res.RowsAffected()
|
|
}
|
|
|
|
// AcceptInvite accepts an invite for a user, adds the user as a member at
|
|
// the invite's scope with the invited role, and removes the invite.
|
|
func (p *Provider) AcceptInvite(ctx context.Context, inviteID, userID uint64) (*model.Membership, error) {
|
|
defer DbMeasureSince(time.Now())
|
|
|
|
user, err := p.GetUser(ctx, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return p.acceptInvite(ctx, inviteID, user)
|
|
}
|
|
|
|
// acceptInvite deletes the invite and adds its grant in one transaction.
|
|
// The grant is made from the row the delete returns, the invite as it is
|
|
// then (a re-invite updates the row in place), so an invite that was
|
|
// withdrawn or accepted after the caller read it is not found and grants
|
|
// nothing; an invite of another email or an expired one rolls back.
|
|
func (p *Provider) acceptInvite(ctx context.Context, inviteID uint64, user *model.User) (*model.Membership, error) {
|
|
tx, err := p.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
defer func() {
|
|
err := tx.Close()
|
|
if err != nil {
|
|
logger.ContextKV(ctx, xlog.ERROR, "reason", "close", "err", err.Error())
|
|
}
|
|
}()
|
|
|
|
txProvider := tx.(*Provider)
|
|
invite, err := txProvider.takeInvite(ctx, inviteID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !strings.EqualFold(user.Email, invite.Email) {
|
|
return nil, errors.Errorf("invite email does not match user email")
|
|
}
|
|
if invite.IsExpired(time.Now()) {
|
|
return nil, errors.Errorf("invite expired")
|
|
}
|
|
|
|
membership, err := txProvider.AddMember(ctx, &model.Membership{
|
|
OrgID: invite.OrgID,
|
|
ProjectID: invite.ProjectID,
|
|
UserID: user.ID,
|
|
Role: invite.Role,
|
|
})
|
|
if err != nil {
|
|
return nil, errors.WithMessage(err, "unable to add member")
|
|
}
|
|
|
|
err = tx.Commit()
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
return membership, nil
|
|
}
|
|
|
|
// takeInvite deletes an invite by ID and returns the deleted row; the
|
|
// delete locks the row until the transaction ends
|
|
func (p *Provider) takeInvite(ctx context.Context, id uint64) (*model.Invite, error) {
|
|
q, name := query.TakeInvite()
|
|
defer DbMeasureQuerySince(name, time.Now())
|
|
|
|
res, err := xdb.QueryRow[model.Invite](ctx, p, q, id)
|
|
if err != nil {
|
|
return nil, xdb.CheckNotFoundError(err, schema.InviteTableInfo.Name, id)
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// AcceptInvites moves the pending invites for a user's email to grants at
|
|
// the invites' scopes, and returns the grants it created. Each invite is
|
|
// accepted in a transaction of its own: an invite whose grant fails is
|
|
// logged, stays pending and is not returned, and one withdrawn since the
|
|
// list is not found and grants nothing.
|
|
func (p *Provider) AcceptInvites(ctx context.Context, user *model.User) (model.MembershipSlice, error) {
|
|
invites, err := p.GetUserInvites(ctx, user.Email)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
logger.ContextKV(ctx, xlog.TRACE,
|
|
"user_id", user.ID,
|
|
"email", user.Email,
|
|
"invites", len(invites))
|
|
|
|
accepted := make(model.MembershipSlice, 0, len(invites))
|
|
for _, inv := range invites {
|
|
m, err := p.acceptInvite(ctx, inv.ID.UInt64(), user)
|
|
if err != nil {
|
|
logger.ContextKV(ctx, xlog.ERROR, "role", inv.Role, "user", user.ID.UnderscoreString(), "err", err.Error())
|
|
continue
|
|
}
|
|
accepted = append(accepted, m)
|
|
}
|
|
return accepted, nil
|
|
}
|