Merge branch 'swarm/oidc-sod'
This commit is contained in:
15 files changed
+1391
-91
No files matched your search
@@ -0,0 +1,23 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE governance.authentication_settings
|
||||
ADD COLUMN oidc_client_secret_sealed bytea NOT NULL DEFAULT '\x'::bytea,
|
||||
ADD COLUMN oidc_groups_claim text NOT NULL DEFAULT '',
|
||||
ADD COLUMN oidc_role_map jsonb NOT NULL DEFAULT '{}',
|
||||
ADD COLUMN sso_only boolean NOT NULL DEFAULT false,
|
||||
ADD COLUMN session_idle_timeout_s integer NOT NULL DEFAULT 0 CHECK (session_idle_timeout_s >= 0),
|
||||
ADD COLUMN session_max_lifetime_s integer NOT NULL DEFAULT 0 CHECK (session_max_lifetime_s >= 0);
|
||||
|
||||
ALTER TABLE governance.account_sessions
|
||||
ADD COLUMN last_seen_at timestamptz NOT NULL DEFAULT now();
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE governance.account_sessions
|
||||
DROP COLUMN last_seen_at;
|
||||
|
||||
ALTER TABLE governance.authentication_settings
|
||||
DROP COLUMN session_max_lifetime_s,
|
||||
DROP COLUMN session_idle_timeout_s,
|
||||
DROP COLUMN sso_only,
|
||||
DROP COLUMN oidc_role_map,
|
||||
DROP COLUMN oidc_groups_claim,
|
||||
DROP COLUMN oidc_client_secret_sealed;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE approvals.requests
|
||||
ADD COLUMN initiator_id text NOT NULL DEFAULT '',
|
||||
ADD COLUMN require_sod boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE approvals.requests
|
||||
DROP COLUMN require_sod,
|
||||
DROP COLUMN initiator_id;
|
||||
@@ -57,6 +57,9 @@ var (
|
||||
// ErrNotSignedIn means the answer came from no signed-in person: the
|
||||
// bootstrap admin token is not a person who may approve.
|
||||
ErrNotSignedIn = errors.New("only a signed-in person can answer an approval")
|
||||
// ErrSelfApprovalForbidden means the person who initiated the action
|
||||
// cannot approve it under four-eyes Segregation of Duties.
|
||||
ErrSelfApprovalForbidden = errors.New("the person who initiated an action cannot approve it")
|
||||
)
|
||||
|
||||
// The kinds of request. An autonomy proposal asks whether an action type may act with one
|
||||
@@ -111,6 +114,12 @@ type Request struct {
|
||||
// the request expired without an answer.
|
||||
AnsweredByID string
|
||||
AnsweredVia string
|
||||
// InitiatorID is the identity ID of the person who initiated the action,
|
||||
// recorded for four-eyes Segregation of Duties.
|
||||
InitiatorID string
|
||||
// RequireSoD enforces four-eyes Segregation of Duties so the initiator
|
||||
// cannot approve the request.
|
||||
RequireSoD bool
|
||||
}
|
||||
|
||||
// Answerer is the account that answered. Display names are not unique, so
|
||||
@@ -188,6 +197,8 @@ type View struct {
|
||||
AnsweredByID string `json:"answered_by_id,omitzero"`
|
||||
AnsweredVia string `json:"answered_via,omitzero"`
|
||||
AnsweredAt time.Time `json:"answered_at,omitzero"`
|
||||
InitiatorID string `json:"initiator_id,omitzero"`
|
||||
RequireSoD bool `json:"require_sod,omitzero"`
|
||||
}
|
||||
|
||||
// StepView is one action of an approval request, as the API shows it.
|
||||
@@ -210,6 +221,7 @@ func (r Request) View() View {
|
||||
Summary: r.Summary, State: r.State, Deadline: r.Deadline, Step: r.Step, StepDeadline: r.StepDeadline,
|
||||
DecisionID: r.DecisionID, RequestedAt: r.RequestedAt, Steps: steps,
|
||||
AnsweredBy: r.AnsweredBy, AnsweredByID: r.AnsweredByID, AnsweredVia: r.AnsweredVia, AnsweredAt: r.AnsweredAt,
|
||||
InitiatorID: r.InitiatorID, RequireSoD: r.RequireSoD,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,20 +310,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, ds []judg
|
||||
if first.ActionTypeID == uuid.Nil {
|
||||
return Request{}, errors.New("approval request needs an action type id")
|
||||
}
|
||||
actions := make([]Step, len(ds))
|
||||
// The request needs the authority of the strictest action it covers, and a
|
||||
// passkey for any action that can't be undone.
|
||||
level := first.Level
|
||||
var changeRequest, passkey bool
|
||||
for i, d := range ds {
|
||||
level = max(level, d.Level)
|
||||
actions[i] = Step{
|
||||
DecisionID: d.ID, Digest: d.Action.Digest, Level: d.Level.String(),
|
||||
Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID,
|
||||
}
|
||||
changeRequest = changeRequest || d.ChangeRequest
|
||||
passkey = passkey || irreversible(d.Action)
|
||||
}
|
||||
actions, level, changeRequest, passkey := buildSteps(ds)
|
||||
changeRequest = changeRequest && m.changes != nil
|
||||
now := m.now().UTC()
|
||||
var total time.Duration
|
||||
@@ -327,6 +326,8 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, ds []judg
|
||||
Summary: SummaryOf(ds), State: StatePending, Deadline: now.Add(total),
|
||||
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true},
|
||||
ChangeRequest: changeRequest,
|
||||
InitiatorID: initiatorOf(ctx),
|
||||
RequireSoD: requireSoDOf(ctx, level == judgement.Escalate || changeRequest || passkey),
|
||||
})
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
@@ -351,6 +352,23 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, ds []judg
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// buildSteps folds the decisions covered by a request into step views,
|
||||
// taking the strictest judgement level and change-request/passkey flags.
|
||||
func buildSteps(ds []judgement.Decision) (steps []Step, level judgement.Level, changeRequest, passkey bool) {
|
||||
steps = make([]Step, len(ds))
|
||||
level = ds[0].Level
|
||||
for i, d := range ds {
|
||||
level = max(level, d.Level)
|
||||
steps[i] = Step{
|
||||
DecisionID: d.ID, Digest: d.Action.Digest, Level: d.Level.String(),
|
||||
Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID,
|
||||
}
|
||||
changeRequest = changeRequest || d.ChangeRequest
|
||||
passkey = passkey || irreversible(d.Action)
|
||||
}
|
||||
return steps, level, changeRequest, passkey
|
||||
}
|
||||
|
||||
// named is how a request's actions are named in a message: the action, or how
|
||||
// many were approved together.
|
||||
func named(r store.Request) string {
|
||||
@@ -372,14 +390,18 @@ func approvalTitle(ds []judgement.Decision) string {
|
||||
|
||||
func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via string, approved bool) (Request, error) {
|
||||
now := m.now().UTC()
|
||||
if _, err := m.pending(ctx, id, now); err != nil {
|
||||
row, err := m.pending(ctx, id, now)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
if err := checkSoD(row, who, approved); err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
state := StateDenied
|
||||
if approved {
|
||||
state = StateApproved
|
||||
}
|
||||
row, err := m.store.Answer(ctx, m.orgID, id, state, who.Name, who.ID, via, now)
|
||||
row, err = m.store.Answer(ctx, m.orgID, id, state, who.Name, who.ID, via, now)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
@@ -497,6 +519,9 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec
|
||||
return false, err
|
||||
}
|
||||
answerer, err := m.channelAnswerer(ctx, who, row)
|
||||
if err == nil {
|
||||
err = checkSoD(row, answerer, approved)
|
||||
}
|
||||
if refusal(err) {
|
||||
identity := who.Issuer + ":" + who.Subject
|
||||
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
|
||||
@@ -575,7 +600,50 @@ func (m *Module) mayAnswer(ctx context.Context, p governance.Principal, row stor
|
||||
// refusal distinguishes a rejected response from an operational error.
|
||||
func refusal(err error) bool {
|
||||
return errors.Is(err, ErrUnlinked) || errors.Is(err, ErrNotApprover) ||
|
||||
errors.Is(err, ErrNeedsFreshAuthentication) || errors.Is(err, ErrNotSignedIn)
|
||||
errors.Is(err, ErrNeedsFreshAuthentication) || errors.Is(err, ErrNotSignedIn) ||
|
||||
errors.Is(err, ErrSelfApprovalForbidden)
|
||||
}
|
||||
|
||||
type (
|
||||
initiatorContextKey struct{}
|
||||
requireSoDContextKey struct{}
|
||||
)
|
||||
|
||||
// WithInitiator attaches the initiator identity ID recorded on created approval requests.
|
||||
func WithInitiator(ctx context.Context, initiatorID string) context.Context {
|
||||
return context.WithValue(ctx, initiatorContextKey{}, strings.TrimSpace(initiatorID))
|
||||
}
|
||||
|
||||
// WithRequireSoD overrides whether created approval requests enforce four-eyes SoD.
|
||||
func WithRequireSoD(ctx context.Context, require bool) context.Context {
|
||||
return context.WithValue(ctx, requireSoDContextKey{}, require)
|
||||
}
|
||||
|
||||
func initiatorOf(ctx context.Context) string {
|
||||
if id, ok := ctx.Value(initiatorContextKey{}).(string); ok && id != "" {
|
||||
return id
|
||||
}
|
||||
if p, ok := governance.PrincipalFromContext(ctx); ok {
|
||||
if p.IdentityID != "" && p.IdentityID != governance.SystemID && p.IdentityID != governance.WorkloadID &&
|
||||
(p.Kind == "" || p.Kind == governance.KindUser) {
|
||||
return string(p.IdentityID)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func requireSoDOf(ctx context.Context, fallback bool) bool {
|
||||
if req, ok := ctx.Value(requireSoDContextKey{}).(bool); ok {
|
||||
return req
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func checkSoD(row store.Request, who Answerer, approved bool) error {
|
||||
if approved && row.RequireSoD && row.InitiatorID != "" && row.InitiatorID == who.ID {
|
||||
return ErrSelfApprovalForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Expire records a timeout without reducing the action type's autonomy:
|
||||
@@ -776,7 +844,7 @@ func requestOf(row store.Request, d judgement.Decision) Request {
|
||||
ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, Digest: row.Digest, ActionTypeID: row.ActionTypeID, RequestedAt: row.CreatedAt,
|
||||
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
|
||||
Level: row.Level, Actions: row.Actions, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
|
||||
Step: row.Step, ChangeRequest: row.ChangeRequest,
|
||||
Step: row.Step, ChangeRequest: row.ChangeRequest, InitiatorID: row.InitiatorID, RequireSoD: row.RequireSoD,
|
||||
}
|
||||
if row.StepDeadline.Valid {
|
||||
r.StepDeadline = row.StepDeadline.Time
|
||||
|
||||
@@ -225,3 +225,74 @@ func TestCoversStillBindsARequestRecordedBeforeItListedItsActions(t *testing.T)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSoDRefusesSelfApproval guards four-eyes Segregation of Duties:
|
||||
// an initiator cannot approve their own SoD-protected request, while
|
||||
// another approver or a denial is permitted and refusals classify properly.
|
||||
func TestSoDRefusesSelfApproval(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
row store.Request
|
||||
who Answerer
|
||||
approved bool
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "same initiator approving SoD request is refused",
|
||||
row: store.Request{InitiatorID: "alice", RequireSoD: true},
|
||||
who: Answerer{ID: "alice", Name: "Alice"},
|
||||
approved: true,
|
||||
wantErr: ErrSelfApprovalForbidden,
|
||||
},
|
||||
{
|
||||
name: "different approver approving SoD request succeeds",
|
||||
row: store.Request{InitiatorID: "alice", RequireSoD: true},
|
||||
who: Answerer{ID: "bob", Name: "Bob"},
|
||||
approved: true,
|
||||
},
|
||||
{
|
||||
name: "initiator denying SoD request succeeds",
|
||||
row: store.Request{InitiatorID: "alice", RequireSoD: true},
|
||||
who: Answerer{ID: "alice", Name: "Alice"},
|
||||
approved: false,
|
||||
},
|
||||
{
|
||||
name: "same initiator succeeds when SoD is not required",
|
||||
row: store.Request{InitiatorID: "alice", RequireSoD: false},
|
||||
who: Answerer{ID: "alice", Name: "Alice"},
|
||||
approved: true,
|
||||
},
|
||||
{
|
||||
name: "empty initiator succeeds even when SoD is enabled",
|
||||
row: store.Request{InitiatorID: "", RequireSoD: true},
|
||||
who: Answerer{ID: "alice", Name: "Alice"},
|
||||
approved: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := checkSoD(tt.row, tt.who, tt.approved)
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("checkSoD = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
if !refusal(ErrSelfApprovalForbidden) {
|
||||
t.Fatal("refusal(ErrSelfApprovalForbidden) = false, want true")
|
||||
}
|
||||
|
||||
userCtx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: "alice", Kind: governance.KindUser})
|
||||
if got := initiatorOf(userCtx); got != "alice" {
|
||||
t.Fatalf("initiatorOf(user) = %q, want alice", got)
|
||||
}
|
||||
botCtx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: "bot-1", Kind: governance.KindBot})
|
||||
if got := initiatorOf(botCtx); got != "" {
|
||||
t.Fatalf("initiatorOf(bot) = %q, want empty", got)
|
||||
}
|
||||
if got := initiatorOf(WithInitiator(botCtx, "charlie")); got != "charlie" {
|
||||
t.Fatalf("initiatorOf(WithInitiator) = %q, want charlie", got)
|
||||
}
|
||||
if !requireSoDOf(WithRequireSoD(t.Context(), true), false) {
|
||||
t.Fatal("requireSoDOf override true returned false")
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,9 @@ func (m *Module) authorise(ctx context.Context, row store.Request, approved bool
|
||||
if err != nil {
|
||||
return Answerer{}, identity, err
|
||||
}
|
||||
if err := checkSoD(row, who, approved); err != nil {
|
||||
return Answerer{}, identity, err
|
||||
}
|
||||
if approved && row.Irreversible {
|
||||
if err := m.confirmed(ctx, row, assertion); err != nil {
|
||||
return Answerer{}, identity, err
|
||||
|
||||
@@ -71,6 +71,9 @@ func TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove(t *testing.T) {
|
||||
{name: "an accepted assertion approves", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}},
|
||||
{name: "a denial needs no assertion", as: signedIn("admin"), row: row(true), approved: false, confirmer: &fakeConfirmer{}},
|
||||
{name: "a developer can't approve with an assertion", as: signedIn("developer"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}, wantErr: ErrNotApprover},
|
||||
{name: "initiator cannot approve their own SoD request", as: signedIn("admin"), row: store.Request{ID: request, Kind: KindAction, Level: judgement.Escalate.String(), InitiatorID: "admin", RequireSoD: true}, approved: true, wantErr: ErrSelfApprovalForbidden},
|
||||
{name: "initiator may deny their own SoD request", as: signedIn("admin"), row: store.Request{ID: request, Kind: KindAction, Level: judgement.Escalate.String(), InitiatorID: "admin", RequireSoD: true}, approved: false},
|
||||
{name: "a different approver may approve a SoD request", as: signedIn("owner"), row: store.Request{ID: request, Kind: KindAction, Level: judgement.Escalate.String(), InitiatorID: "admin", RequireSoD: true}, approved: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
@@ -90,6 +90,8 @@ type Request struct {
|
||||
// Counted is whether the approval was counted toward loosening its action type.
|
||||
Counted bool `db:"counted"`
|
||||
DiscardedBecause sql.NullString `db:"discarded_because"`
|
||||
InitiatorID string `db:"initiator_id"`
|
||||
RequireSoD bool `db:"require_sod"`
|
||||
}
|
||||
|
||||
// Store is the approvals module's Postgres store.
|
||||
@@ -114,7 +116,7 @@ func (s *Store) change() {
|
||||
|
||||
const requestColumns = `id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind,
|
||||
target_id, level, actions, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via,
|
||||
step, step_deadline, change_request, counted, discarded_because`
|
||||
step, step_deadline, change_request, counted, discarded_because, initiator_id, require_sod`
|
||||
|
||||
// Put inserts r or returns the existing request for the same organisation,
|
||||
// run and key.
|
||||
@@ -126,12 +128,12 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
|
||||
}
|
||||
err = s.db.GetContext(ctx, &out, `
|
||||
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id,
|
||||
installation_scope, action, target_kind, target_id, level, actions, irreversible, summary, state, deadline, step_deadline, change_request)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb, $17, $18, $19, $20, $21, $22)
|
||||
installation_scope, action, target_kind, target_id, level, actions, irreversible, summary, state, deadline, step_deadline, change_request, initiator_id, require_sod)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb, $17, $18, $19, $20, $21, $22, $23, $24)
|
||||
ON CONFLICT (org_id, run_id, key) DO NOTHING
|
||||
RETURNING `+requestColumns,
|
||||
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.ActionTypeID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind,
|
||||
r.TargetID, r.Level, string(actions), r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest)
|
||||
r.TargetID, r.Level, string(actions), r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest, r.InitiatorID, r.RequireSoD)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -100,6 +102,7 @@ func (m *Module) RegisterAccounts(api huma.API) {
|
||||
httpapi.Register(api, httpapi.Public(), op("finish-passkey-sign-in", http.MethodPost, "/api/auth/passkey/finish", "Finish signing in with a passkey", 0), m.finishPasskeySignIn)
|
||||
httpapi.Register(api, httpapi.Public(), op("begin-oidc-sign-in", http.MethodGet, "/oauth2/login", "Send the browser to the identity provider", http.StatusSeeOther), m.beginOIDC)
|
||||
httpapi.Register(api, httpapi.Public(), op("finish-oidc-sign-in", http.MethodGet, oidcCallbackPath, "Complete the identity provider's sign-in", http.StatusSeeOther), m.finishOIDC)
|
||||
httpapi.Register(api, httpapi.Public(), op("oidc-backchannel-logout", http.MethodPost, oidcBackchannelLogoutPath, "Handle OIDC back-channel logout notifications", http.StatusOK), m.backchannelLogout)
|
||||
|
||||
httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("change-password", http.MethodPost, "/api/account/password", "Change your password", http.StatusNoContent), m.changePassword)
|
||||
httpapi.Register(api, httpapi.Authorized(ActionCreate, KindAccount), op("create-recovery-code", http.MethodPost, "/api/account/recovery", "Create a recovery code", 0), m.createRecoveryCode)
|
||||
@@ -121,6 +124,8 @@ func (m *Module) RegisterAccounts(api huma.API) {
|
||||
// accountError turns an account failure into the status a person can act on.
|
||||
func (m *Module) accountError(ctx context.Context, err error) error {
|
||||
switch {
|
||||
case errors.Is(err, ErrSSOOnly):
|
||||
return huma.Error403Forbidden("Password sign-in is disabled when SSO-only mode is enabled.")
|
||||
case refused(err):
|
||||
return huma.Error401Unauthorized(httpapi.ErrUnauthenticated.Error())
|
||||
case errors.Is(err, ErrSetupComplete):
|
||||
@@ -159,6 +164,7 @@ type authStatusBody struct {
|
||||
SetupRequired bool `json:"setup_required"`
|
||||
User *Identity `json:"user"`
|
||||
OIDC bool `json:"oidc"`
|
||||
SSOOnly bool `json:"sso_only"`
|
||||
PublicURL string `json:"public_url"`
|
||||
Instance string `json:"instance"`
|
||||
}
|
||||
@@ -189,6 +195,7 @@ func (m *Module) authStatus(ctx context.Context, in *sessionInput) (*authStatusR
|
||||
}
|
||||
out.PublicURL = settings.PublicURL
|
||||
out.OIDC = settings.PublicURL != "" && settings.OIDCIssuer != ""
|
||||
out.SSOOnly = settings.SSOOnly
|
||||
return &authStatusReply{CacheControl: "no-store", Body: out}, nil
|
||||
}
|
||||
|
||||
@@ -336,11 +343,17 @@ func (m *Module) getAuthentication(ctx context.Context, _ *struct{}) (*httpapi.R
|
||||
type authenticationInput struct {
|
||||
Session string `cookie:"archie_session"`
|
||||
Body struct {
|
||||
PublicURL string `json:"public_url"`
|
||||
OIDCIssuer string `json:"oidc_issuer,omitempty"`
|
||||
OIDCAudience string `json:"oidc_audience,omitempty"`
|
||||
OIDCClientID string `json:"oidc_client_id,omitempty"`
|
||||
TrustedProxies []string `json:"trusted_proxies,omitempty"`
|
||||
PublicURL string `json:"public_url"`
|
||||
OIDCIssuer string `json:"oidc_issuer,omitempty"`
|
||||
OIDCAudience string `json:"oidc_audience,omitempty"`
|
||||
OIDCClientID string `json:"oidc_client_id,omitempty"`
|
||||
OIDCClientSecret string `json:"oidc_client_secret,omitempty"`
|
||||
OIDCGroupsClaim string `json:"oidc_groups_claim,omitempty"`
|
||||
OIDCRoleMap map[string]Role `json:"oidc_role_map,omitempty"`
|
||||
SSOOnly bool `json:"sso_only,omitempty"`
|
||||
SessionIdleTimeoutS int `json:"session_idle_timeout_s,omitempty"`
|
||||
SessionMaxLifetimeS int `json:"session_max_lifetime_s,omitempty"`
|
||||
TrustedProxies []string `json:"trusted_proxies,omitempty"`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,9 +361,22 @@ func (m *Module) putAuthentication(ctx context.Context, in *authenticationInput)
|
||||
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := m.SaveAuthenticationSettings(ctx, AuthenticationSettings(in.Body))
|
||||
b := in.Body
|
||||
err := m.SaveAuthenticationSettings(ctx, AuthenticationSettings{
|
||||
PublicURL: b.PublicURL,
|
||||
OIDCIssuer: b.OIDCIssuer,
|
||||
OIDCAudience: b.OIDCAudience,
|
||||
OIDCClientID: b.OIDCClientID,
|
||||
OIDCClientSecret: b.OIDCClientSecret,
|
||||
OIDCGroupsClaim: b.OIDCGroupsClaim,
|
||||
OIDCRoleMap: b.OIDCRoleMap,
|
||||
SSOOnly: b.SSOOnly,
|
||||
SessionIdleTimeoutS: b.SessionIdleTimeoutS,
|
||||
SessionMaxLifetimeS: b.SessionMaxLifetimeS,
|
||||
TrustedProxies: b.TrustedProxies,
|
||||
})
|
||||
if errors.Is(err, ErrInvalidIdentity) {
|
||||
return nil, huma.Error400BadRequest("Use a valid instance origin, trusted proxies that are addresses or CIDR ranges, and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.")
|
||||
return nil, huma.Error400BadRequest("Use a valid instance origin, trusted proxies that are addresses or CIDR ranges, non-negative session timeouts, and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
@@ -673,8 +699,8 @@ type oidcCallbackInput struct {
|
||||
}
|
||||
|
||||
// finishOIDC checks the state it issued, exchanges the code with the PKCE
|
||||
// verifier it issued, and opens a local session no longer than the
|
||||
// provider's.
|
||||
// verifier it issued, syncs mapped group roles, and opens a local session
|
||||
// no longer than the provider's.
|
||||
func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redirectReply, error) {
|
||||
if in.ProviderError != "" {
|
||||
return nil, m.accountError(ctx, fmt.Errorf("%w: provider returned %s", ErrCredentialRejected, in.ProviderError))
|
||||
@@ -682,6 +708,10 @@ func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redire
|
||||
if in.WantState == "" || !sameToken(in.WantState, in.State) || in.Verifier == "" {
|
||||
return nil, m.accountError(ctx, fmt.Errorf("%w: sign-in state did not match", ErrCredentialRejected))
|
||||
}
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
flow, err := m.oidc.flow(ctx, m)
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
@@ -694,6 +724,9 @@ func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redire
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
if err := syncOIDCRole(ctx, m.log, m, value.ID, session.Credential.Groups, settings); err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
p, err := m.PrincipalFor(ctx, value.ID)
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
@@ -714,6 +747,72 @@ func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redire
|
||||
}, nil
|
||||
}
|
||||
|
||||
type membershipSyncer interface {
|
||||
OrgForIdentity(context.Context, IdentityID) (OrgID, error)
|
||||
EnsureMembership(context.Context, Membership) error
|
||||
}
|
||||
|
||||
func syncOIDCRole(ctx context.Context, log *slog.Logger, orgs membershipSyncer, id IdentityID, groups []string, settings AuthenticationSettings) error {
|
||||
if strings.TrimSpace(settings.OIDCGroupsClaim) == "" || len(settings.OIDCRoleMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
role, ok := mapGroupsToRole(groups, settings.OIDCRoleMap)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
orgID, err := orgs.OrgForIdentity(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if orgID == "" {
|
||||
orgID = DefaultOrgID
|
||||
}
|
||||
if err := orgs.EnsureMembership(ctx, Membership{IdentityID: id, OrgID: orgID, Role: role}); err != nil {
|
||||
if errors.Is(err, ErrLastOwner) {
|
||||
if log != nil {
|
||||
log.WarnContext(ctx, "skipping OIDC role downgrade for last active owner", "identity", id, "org", orgID, "mapped_role", role)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type backchannelLogoutInput struct {
|
||||
RawBody []byte
|
||||
}
|
||||
|
||||
type backchannelLogoutReply struct {
|
||||
CacheControl string `header:"Cache-Control"`
|
||||
}
|
||||
|
||||
func (m *Module) backchannelLogout(ctx context.Context, in *backchannelLogoutInput) (*backchannelLogoutReply, error) {
|
||||
form, err := url.ParseQuery(string(in.RawBody))
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("invalid form payload")
|
||||
}
|
||||
rawToken := strings.TrimSpace(form.Get("logout_token"))
|
||||
if rawToken == "" {
|
||||
return nil, huma.Error400BadRequest("logout_token is required")
|
||||
}
|
||||
flow, err := m.oidc.flow(ctx, m)
|
||||
if errors.Is(err, ErrNoCredential) {
|
||||
return nil, huma.Error404NotFound("no identity provider is configured")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
sub, err := flow.VerifyLogoutToken(ctx, rawToken)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("invalid logout_token")
|
||||
}
|
||||
if err := m.RevokeSessionsBySubject(ctx, sub.Issuer, sub.Subject); err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
return &backchannelLogoutReply{CacheControl: "no-store"}, nil
|
||||
}
|
||||
|
||||
func randomState() (string, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
|
||||
@@ -84,7 +84,7 @@ func actingAs(ctx context.Context, p Principal) context.Context {
|
||||
// refused reports whether err says the credential was not accepted, as
|
||||
// opposed to the lookup failing.
|
||||
func refused(err error) bool {
|
||||
for _, target := range []error{ErrNoCredential, ErrCredentialRejected, ErrIdentityNotFound, ErrIdentityInactive, ErrSubjectUnbound} {
|
||||
for _, target := range []error{ErrNoCredential, ErrCredentialRejected, ErrIdentityNotFound, ErrIdentityInactive, ErrSubjectUnbound, ErrSSOOnly} {
|
||||
if errors.Is(err, target) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/prompts"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
)
|
||||
|
||||
@@ -288,6 +289,7 @@ type Module struct {
|
||||
store *store.Store
|
||||
log *slog.Logger
|
||||
credentials Credentials
|
||||
sealer *seal.Sealer
|
||||
authorizer atomic.Pointer[Authorizer]
|
||||
oidc *oidcLogin
|
||||
setup *SetupSignal
|
||||
@@ -311,6 +313,9 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
|
||||
// resolves through.
|
||||
func (m *Module) UseCredentials(c Credentials) { m.credentials = c }
|
||||
|
||||
// UseSealer gives the module the sealer used to encrypt OIDC client secrets at rest.
|
||||
func (m *Module) UseSealer(s *seal.Sealer) { m.sealer = s }
|
||||
|
||||
// UseAuthorizer gives the module the live policy chain that administrative
|
||||
// writes are checked against.
|
||||
func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer.Store(&a) }
|
||||
|
||||
@@ -49,6 +49,7 @@ var (
|
||||
ErrSubjectUnbound = errors.New("credential subject is not bound to an identity")
|
||||
ErrIdentityInactive = errors.New("identity may not act")
|
||||
ErrSetupComplete = errors.New("administrator has already been set up")
|
||||
ErrSSOOnly = errors.New("password sign-in is disabled by SSO-only policy")
|
||||
)
|
||||
|
||||
// Identity is a persistent actor (user, bot, service account, or system) and
|
||||
@@ -254,6 +255,7 @@ type Credential struct {
|
||||
Subject Subject
|
||||
Email string
|
||||
Scopes []string
|
||||
Groups []string
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
@@ -455,17 +457,24 @@ type AccountSecurity interface {
|
||||
// AuthenticationSettings stores the instance's public origin, its trusted
|
||||
// reverse proxies and the OIDC parameters.
|
||||
type AuthenticationSettings struct {
|
||||
PublicURL string `json:"public_url"`
|
||||
OIDCIssuer string `json:"oidc_issuer"`
|
||||
OIDCAudience string `json:"oidc_audience"`
|
||||
OIDCClientID string `json:"oidc_client_id"`
|
||||
PublicURL string `json:"public_url"`
|
||||
OIDCIssuer string `json:"oidc_issuer"`
|
||||
OIDCAudience string `json:"oidc_audience"`
|
||||
OIDCClientID string `json:"oidc_client_id"`
|
||||
OIDCClientSecret string `json:"oidc_client_secret,omitempty" writeOnly:"true"`
|
||||
OIDCClientSecretSet bool `json:"oidc_client_secret_set" readOnly:"true"`
|
||||
OIDCGroupsClaim string `json:"oidc_groups_claim,omitempty"`
|
||||
OIDCRoleMap map[string]Role `json:"oidc_role_map,omitempty"`
|
||||
SSOOnly bool `json:"sso_only"`
|
||||
SessionIdleTimeoutS int `json:"session_idle_timeout_s"`
|
||||
SessionMaxLifetimeS int `json:"session_max_lifetime_s"`
|
||||
// TrustedProxies are the addresses and CIDR ranges of reverse proxies whose
|
||||
// X-Forwarded-For header webhook intake uses as the client address.
|
||||
TrustedProxies []string `json:"trusted_proxies"`
|
||||
}
|
||||
|
||||
// Validate checks that PublicURL is a valid origin, the trusted proxies are
|
||||
// addresses or ranges, and OIDC fields are paired.
|
||||
// addresses or ranges, session timeouts are non-negative, and OIDC fields are paired.
|
||||
func (s AuthenticationSettings) Validate() error {
|
||||
if !validInstanceOrigin(s.PublicURL) {
|
||||
return ErrInvalidIdentity
|
||||
@@ -473,8 +482,15 @@ func (s AuthenticationSettings) Validate() error {
|
||||
if _, err := normalizeProxies(s.TrustedProxies); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.SessionIdleTimeoutS < 0 || s.SessionMaxLifetimeS < 0 {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
return s.validateOIDC()
|
||||
}
|
||||
|
||||
func (s AuthenticationSettings) validateOIDC() error {
|
||||
if s.OIDCIssuer == "" {
|
||||
if s.OIDCClientID != "" || s.OIDCAudience != "" {
|
||||
if s.hasPartialOIDC() || s.SSOOnly {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
return nil
|
||||
@@ -482,6 +498,28 @@ func (s AuthenticationSettings) Validate() error {
|
||||
if !validProviderIssuer(s.OIDCIssuer) || strings.TrimSpace(s.OIDCClientID) == "" || strings.TrimSpace(s.OIDCAudience) == "" {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
if s.OIDCClientSecret != "" && strings.TrimSpace(s.OIDCClientSecret) == "" {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
return validateOIDCRoleMap(s.OIDCGroupsClaim, s.OIDCRoleMap)
|
||||
}
|
||||
|
||||
func (s AuthenticationSettings) hasPartialOIDC() bool {
|
||||
return s.OIDCClientID != "" || s.OIDCAudience != "" || s.OIDCClientSecret != "" || s.OIDCGroupsClaim != "" || len(s.OIDCRoleMap) > 0
|
||||
}
|
||||
|
||||
func validateOIDCRoleMap(groupsClaim string, roleMap map[string]Role) error {
|
||||
if len(roleMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(groupsClaim) == "" {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
for group, role := range roleMap {
|
||||
if strings.TrimSpace(group) == "" || role == RoleWorkload || role.Validate() != nil {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -25,14 +25,28 @@ type AccountRow struct {
|
||||
|
||||
// AuthSettingsRow stores instance public URL and OIDC configuration.
|
||||
type AuthSettingsRow struct {
|
||||
PublicURL string `db:"public_url"`
|
||||
OIDCIssuer string `db:"oidc_issuer"`
|
||||
OIDCAudience string `db:"oidc_audience"`
|
||||
OIDCClientID string `db:"oidc_client_id"`
|
||||
PublicURL string `db:"public_url"`
|
||||
OIDCIssuer string `db:"oidc_issuer"`
|
||||
OIDCAudience string `db:"oidc_audience"`
|
||||
OIDCClientID string `db:"oidc_client_id"`
|
||||
OIDCClientSecretSealed []byte `db:"oidc_client_secret_sealed"`
|
||||
OIDCGroupsClaim string `db:"oidc_groups_claim"`
|
||||
OIDCRoleMap []byte `db:"oidc_role_map"`
|
||||
SSOOnly bool `db:"sso_only"`
|
||||
SessionIdleTimeoutS int `db:"session_idle_timeout_s"`
|
||||
SessionMaxLifetimeS int `db:"session_max_lifetime_s"`
|
||||
// TrustedProxies is a JSON array of addresses and CIDR ranges.
|
||||
TrustedProxies []byte `db:"trusted_proxies"`
|
||||
}
|
||||
|
||||
// AccountSessionRow joins a session's lifecycle timestamps with its identity.
|
||||
type AccountSessionRow struct {
|
||||
IdentityRow
|
||||
IssuedAt time.Time `db:"issued_at"`
|
||||
LastSeenAt time.Time `db:"last_seen_at"`
|
||||
ExpiresAt time.Time `db:"expires_at"`
|
||||
}
|
||||
|
||||
// RegisterAccountParams carries the validated inputs to create a user account.
|
||||
type RegisterAccountParams struct {
|
||||
IdentityID string
|
||||
@@ -128,12 +142,13 @@ func writeAccountTx(ctx context.Context, tx *sqlx.Tx, p RegisterAccountParams, o
|
||||
return tx.GetContext(ctx, out, `SELECT `+identityCols+` FROM governance.identities WHERE id = $1`, p.IdentityID)
|
||||
}
|
||||
|
||||
// SignInAccount authenticates email with verify, applies lockout rules, and opens a session.
|
||||
// SignInAccount authenticates email with verify, applies lockout and policy rules, and opens a session.
|
||||
func (s *Store) SignInAccount(
|
||||
ctx context.Context,
|
||||
email, tokenHash string,
|
||||
expires time.Time,
|
||||
verify func(passwordHash string) bool,
|
||||
allowSignIn func(identityID string, isOrgOwner bool) error,
|
||||
) (IdentityRow, error) {
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
if err != nil {
|
||||
@@ -167,6 +182,19 @@ func (s *Store) SignInAccount(
|
||||
if id.Lifecycle != "active" {
|
||||
return IdentityRow{}, ErrCredentialRejected
|
||||
}
|
||||
if allowSignIn != nil {
|
||||
var isOwner bool
|
||||
if err := tx.GetContext(ctx, &isOwner, `
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM governance.memberships
|
||||
WHERE identity_id = $1 AND workspace_id IS NULL AND role = 'owner'
|
||||
)`, acc.IdentityID); err != nil {
|
||||
return IdentityRow{}, err
|
||||
}
|
||||
if err := allowSignIn(acc.IdentityID, isOwner); err != nil {
|
||||
return IdentityRow{}, err
|
||||
}
|
||||
}
|
||||
if err := openSignInSessionTx(ctx, tx, acc.IdentityID, tokenHash, expires); err != nil {
|
||||
return IdentityRow{}, err
|
||||
}
|
||||
@@ -207,20 +235,41 @@ func openSignInSessionTx(ctx context.Context, tx *sqlx.Tx, identityID, tokenHash
|
||||
return err
|
||||
}
|
||||
|
||||
// ResolveAccountSession resolves a session token hash to its active identity.
|
||||
func (s *Store) ResolveAccountSession(ctx context.Context, tokenHash string) (IdentityRow, error) {
|
||||
var out IdentityRow
|
||||
// GetAccountSession returns a session's identity and lifecycle timestamps.
|
||||
func (s *Store) GetAccountSession(ctx context.Context, tokenHash string) (AccountSessionRow, error) {
|
||||
var out AccountSessionRow
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
|
||||
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at,
|
||||
s.issued_at, s.last_seen_at, s.expires_at
|
||||
FROM governance.account_sessions s
|
||||
JOIN governance.identities i ON i.id = s.identity_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now() AND i.lifecycle = 'active'`, tokenHash)
|
||||
WHERE s.token_hash = $1`, tokenHash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return IdentityRow{}, ErrCredentialRejected
|
||||
return AccountSessionRow{}, ErrCredentialRejected
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
// TouchAccountSession refreshes last_seen_at on an active session.
|
||||
func (s *Store) TouchAccountSession(ctx context.Context, tokenHash string, at time.Time) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE governance.account_sessions SET last_seen_at = $2 WHERE token_hash = $1`, tokenHash, at)
|
||||
return err
|
||||
}
|
||||
|
||||
// RevokeSessionsBySubject deletes every session belonging to the identity bound to (issuer, subject).
|
||||
func (s *Store) RevokeSessionsBySubject(ctx context.Context, issuer, subject string) (int64, error) {
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM governance.account_sessions s
|
||||
USING governance.identity_subjects sub
|
||||
WHERE s.identity_id = sub.identity_id
|
||||
AND sub.issuer = $1
|
||||
AND sub.subject = $2`, issuer, subject)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("revoke sessions by subject: %w", err)
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// DeleteAccountSession removes a session token.
|
||||
func (s *Store) DeleteAccountSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM governance.account_sessions WHERE token_hash = $1`, tokenHash)
|
||||
@@ -329,7 +378,10 @@ func (s *Store) RecoverAccount(ctx context.Context, email, recoveryHash, newPass
|
||||
func (s *Store) AuthenticationSettings(ctx context.Context) (AuthSettingsRow, error) {
|
||||
var out AuthSettingsRow
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
SELECT public_url, oidc_issuer, oidc_audience, oidc_client_id, trusted_proxies
|
||||
SELECT public_url, oidc_issuer, oidc_audience, oidc_client_id,
|
||||
oidc_client_secret_sealed, oidc_groups_claim, oidc_role_map,
|
||||
sso_only, session_idle_timeout_s, session_max_lifetime_s,
|
||||
trusted_proxies
|
||||
FROM governance.authentication_settings WHERE singleton`)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return AuthSettingsRow{}, nil
|
||||
@@ -342,11 +394,30 @@ func (s *Store) AuthenticationSettings(ctx context.Context) (AuthSettingsRow, er
|
||||
|
||||
// SaveAuthenticationSettings updates authentication settings, refusing origin changes when passkeys exist.
|
||||
func (s *Store) SaveAuthenticationSettings(ctx context.Context, row AuthSettingsRow) (updated bool, err error) {
|
||||
var secretArg any
|
||||
if row.OIDCClientSecretSealed != nil {
|
||||
secretArg = row.OIDCClientSecretSealed
|
||||
}
|
||||
roleMap := "{}"
|
||||
if len(row.OIDCRoleMap) > 0 {
|
||||
roleMap = string(row.OIDCRoleMap)
|
||||
}
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
UPDATE governance.authentication_settings
|
||||
SET public_url = $1, oidc_issuer = $2, oidc_audience = $3, oidc_client_id = $4, trusted_proxies = $5
|
||||
SET public_url = $1,
|
||||
oidc_issuer = $2,
|
||||
oidc_audience = $3,
|
||||
oidc_client_id = $4,
|
||||
trusted_proxies = $5,
|
||||
oidc_client_secret_sealed = COALESCE($6::bytea, oidc_client_secret_sealed),
|
||||
oidc_groups_claim = $7,
|
||||
oidc_role_map = $8::jsonb,
|
||||
sso_only = $9,
|
||||
session_idle_timeout_s = $10,
|
||||
session_max_lifetime_s = $11
|
||||
WHERE singleton AND (public_url = $1 OR NOT EXISTS (SELECT 1 FROM governance.passkeys))`,
|
||||
row.PublicURL, row.OIDCIssuer, row.OIDCAudience, row.OIDCClientID, string(row.TrustedProxies))
|
||||
row.PublicURL, row.OIDCIssuer, row.OIDCAudience, row.OIDCClientID, string(row.TrustedProxies),
|
||||
secretArg, row.OIDCGroupsClaim, roleMap, row.SSOOnly, row.SessionIdleTimeoutS, row.SessionMaxLifetimeS)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("save authentication settings: %w", err)
|
||||
}
|
||||
|
||||
+163
-16
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
gooidc "github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
@@ -14,6 +15,16 @@ import (
|
||||
// the provider returns the browser to the path it was given.
|
||||
const oidcCallbackPath = "/oauth2/callback"
|
||||
|
||||
// oidcBackchannelLogoutPath receives OIDC Back-Channel Logout 1.0 notifications.
|
||||
const oidcBackchannelLogoutPath = "/oauth2/backchannel-logout"
|
||||
|
||||
const backchannelLogoutEvent = "http://schemas.openid.net/event/backchannel-logout"
|
||||
|
||||
type oidcConfigSource interface {
|
||||
AuthenticationSettings(ctx context.Context) (AuthenticationSettings, error)
|
||||
oidcClientSecret(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// oidcLogin runs the browser sign-in against the provider the authentication
|
||||
// settings name. It keeps the provider's discovery and signing-key cache
|
||||
// until the settings change, so a change applies without a restart.
|
||||
@@ -25,7 +36,7 @@ type oidcLogin struct {
|
||||
|
||||
// flow returns the authorisation code flow for the saved settings, or
|
||||
// ErrNoCredential when no provider is configured.
|
||||
func (o *oidcLogin) flow(ctx context.Context, settings AuthenticationSettingsStore) (*oidcFlow, error) {
|
||||
func (o *oidcLogin) flow(ctx context.Context, settings oidcConfigSource) (*oidcFlow, error) {
|
||||
value, err := settings.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -33,6 +44,10 @@ func (o *oidcLogin) flow(ctx context.Context, settings AuthenticationSettingsSto
|
||||
if value.PublicURL == "" || value.OIDCIssuer == "" {
|
||||
return nil, ErrNoCredential
|
||||
}
|
||||
secret, err := settings.oidcClientSecret(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
if o.provider == nil || o.current.OIDCIssuer != value.OIDCIssuer || o.current.OIDCAudience != value.OIDCAudience {
|
||||
@@ -42,7 +57,7 @@ func (o *oidcLogin) flow(ctx context.Context, settings AuthenticationSettingsSto
|
||||
}
|
||||
o.provider, o.current = provider, value
|
||||
}
|
||||
return newOIDCFlow(o.provider, value.OIDCClientID, value.PublicURL+oidcCallbackPath)
|
||||
return newOIDCFlow(o.provider, value.OIDCClientID, secret, value.PublicURL+oidcCallbackPath, value.OIDCGroupsClaim)
|
||||
}
|
||||
|
||||
// oidcProvider discovers the identity provider on first use and keeps the
|
||||
@@ -83,19 +98,28 @@ func (p *oidcProvider) get(ctx context.Context) (*gooidc.Provider, error) {
|
||||
return discovered, nil
|
||||
}
|
||||
|
||||
// oidcFlow runs the authorisation code flow with PKCE. Discovery, the code
|
||||
// exchange, PKCE and token verification are the libraries'.
|
||||
// oidcFlow runs the authorisation code flow with PKCE and optional confidential
|
||||
// client authentication. Discovery, the code exchange, PKCE and token verification
|
||||
// are the libraries'.
|
||||
type oidcFlow struct {
|
||||
provider *oidcProvider
|
||||
clientID string
|
||||
redirectURL string
|
||||
provider *oidcProvider
|
||||
clientID string
|
||||
clientSecret string
|
||||
redirectURL string
|
||||
groupsClaim string
|
||||
}
|
||||
|
||||
func newOIDCFlow(provider *oidcProvider, clientID, redirectURL string) (*oidcFlow, error) {
|
||||
func newOIDCFlow(provider *oidcProvider, clientID, clientSecret, redirectURL, groupsClaim string) (*oidcFlow, error) {
|
||||
if strings.TrimSpace(clientID) == "" {
|
||||
return nil, fmt.Errorf("oidc: client id is required for the browser flow")
|
||||
}
|
||||
return &oidcFlow{provider: provider, clientID: clientID, redirectURL: redirectURL}, nil
|
||||
return &oidcFlow{
|
||||
provider: provider,
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
redirectURL: redirectURL,
|
||||
groupsClaim: strings.TrimSpace(groupsClaim),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *oidcFlow) oauth(ctx context.Context) (oauth2.Config, error) {
|
||||
@@ -104,9 +128,10 @@ func (f *oidcFlow) oauth(ctx context.Context) (oauth2.Config, error) {
|
||||
return oauth2.Config{}, err
|
||||
}
|
||||
return oauth2.Config{
|
||||
ClientID: f.clientID,
|
||||
Endpoint: discovered.Endpoint(),
|
||||
RedirectURL: f.redirectURL,
|
||||
ClientID: f.clientID,
|
||||
ClientSecret: f.clientSecret,
|
||||
Endpoint: discovered.Endpoint(),
|
||||
RedirectURL: f.redirectURL,
|
||||
// openid makes the provider return a subject at all; profile and
|
||||
// email make a name available for display.
|
||||
Scopes: []string{gooidc.ScopeOpenID, "profile", "email"},
|
||||
@@ -156,7 +181,7 @@ func (f *oidcFlow) Exchange(ctx context.Context, code, codeVerifier string) (Pro
|
||||
if verified.Nonce != oauth2.S256ChallengeFromVerifier(codeVerifier) {
|
||||
return ProviderSession{}, fmt.Errorf("%w: ID token nonce mismatch", ErrCredentialRejected)
|
||||
}
|
||||
credential, err := credentialOf(verified)
|
||||
credential, err := credentialOf(verified, f.groupsClaim)
|
||||
if err != nil {
|
||||
return ProviderSession{}, err
|
||||
}
|
||||
@@ -167,9 +192,49 @@ func (f *oidcFlow) Exchange(ctx context.Context, code, codeVerifier string) (Pro
|
||||
return ProviderSession{Credential: credential, Token: rawIDToken, Expires: expires}, nil
|
||||
}
|
||||
|
||||
// VerifyLogoutToken validates an OIDC Back-Channel Logout 1.0 JWT and returns
|
||||
// the provider subject whose sessions must be revoked.
|
||||
func (f *oidcFlow) VerifyLogoutToken(ctx context.Context, rawToken string) (Subject, error) {
|
||||
rawToken = strings.TrimSpace(rawToken)
|
||||
if rawToken == "" {
|
||||
return Subject{}, fmt.Errorf("%w: logout_token is required", ErrCredentialRejected)
|
||||
}
|
||||
discovered, err := f.provider.get(ctx)
|
||||
if err != nil {
|
||||
return Subject{}, err
|
||||
}
|
||||
// Back-channel logout tokens may omit exp per OIDC Back-Channel Logout 1.0 §2.4.
|
||||
verified, err := discovered.Verifier(&gooidc.Config{ClientID: f.clientID, SkipExpiryCheck: true}).Verify(ctx, rawToken)
|
||||
if err != nil {
|
||||
return Subject{}, fmt.Errorf("%w: verify logout token: %w", ErrCredentialRejected, err)
|
||||
}
|
||||
if !verified.Expiry.IsZero() && !time.Now().Before(verified.Expiry) {
|
||||
return Subject{}, fmt.Errorf("%w: logout token expired", ErrCredentialRejected)
|
||||
}
|
||||
var claims struct {
|
||||
Subject string `json:"sub"`
|
||||
Nonce string `json:"nonce"`
|
||||
Events map[string]any `json:"events"`
|
||||
}
|
||||
if err := verified.Claims(&claims); err != nil {
|
||||
return Subject{}, fmt.Errorf("%w: decode logout token claims: %w", ErrCredentialRejected, err)
|
||||
}
|
||||
if claims.Nonce != "" {
|
||||
return Subject{}, fmt.Errorf("%w: logout token must not contain nonce", ErrCredentialRejected)
|
||||
}
|
||||
if _, ok := claims.Events[backchannelLogoutEvent]; !ok {
|
||||
return Subject{}, fmt.Errorf("%w: logout token missing backchannel-logout event", ErrCredentialRejected)
|
||||
}
|
||||
sub := strings.TrimSpace(claims.Subject)
|
||||
if sub == "" {
|
||||
return Subject{}, fmt.Errorf("%w: logout token missing sub", ErrCredentialRejected)
|
||||
}
|
||||
return Subject{Issuer: verified.Issuer, Subject: sub}, nil
|
||||
}
|
||||
|
||||
// credentialOf reads what a verified token proved. Claims are read only after
|
||||
// verification: an unverified token selects nothing.
|
||||
func credentialOf(token *gooidc.IDToken) (Credential, error) {
|
||||
func credentialOf(token *gooidc.IDToken, groupsClaim string) (Credential, error) {
|
||||
var claims struct {
|
||||
Subject string `json:"sub"`
|
||||
ClientID string `json:"client_id"`
|
||||
@@ -178,7 +243,9 @@ func credentialOf(token *gooidc.IDToken) (Credential, error) {
|
||||
Email string `json:"email"`
|
||||
Verified bool `json:"email_verified"`
|
||||
}
|
||||
_ = token.Claims(&claims)
|
||||
if err := token.Claims(&claims); err != nil {
|
||||
return Credential{}, fmt.Errorf("%w: decode token claims: %w", ErrCredentialRejected, err)
|
||||
}
|
||||
subject := Subject{Issuer: token.Issuer, Subject: strings.TrimSpace(claims.Subject)}
|
||||
if subject.Subject == "" {
|
||||
subject.Subject = strings.TrimSpace(claims.ClientID)
|
||||
@@ -194,5 +261,85 @@ func credentialOf(token *gooidc.IDToken) (Credential, error) {
|
||||
if len(scopes) == 0 {
|
||||
scopes = strings.Fields(claims.Scope)
|
||||
}
|
||||
return Credential{Subject: subject, Email: email, Scopes: scopes, Expires: token.Expiry}, nil
|
||||
var groups []string
|
||||
if name := strings.TrimSpace(groupsClaim); name != "" {
|
||||
var raw map[string]any
|
||||
if err := token.Claims(&raw); err == nil {
|
||||
groups = extractGroupsClaim(raw, name)
|
||||
}
|
||||
}
|
||||
return Credential{Subject: subject, Email: email, Scopes: scopes, Groups: groups, Expires: token.Expiry}, nil
|
||||
}
|
||||
|
||||
// extractGroupsClaim reads string or string-slice group claims from raw token claims.
|
||||
func extractGroupsClaim(raw map[string]any, claim string) []string {
|
||||
if raw == nil || claim == "" {
|
||||
return nil
|
||||
}
|
||||
val, ok := raw[claim]
|
||||
if !ok || val == nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
switch v := val.(type) {
|
||||
case string:
|
||||
if s := strings.TrimSpace(v); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
case []string:
|
||||
for _, item := range v {
|
||||
if s := strings.TrimSpace(item); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, item := range v {
|
||||
if s, ok := item.(string); ok {
|
||||
if trimmed := strings.TrimSpace(s); trimmed != "" {
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mapGroupsToRole selects the highest-privilege mapped role among groups.
|
||||
func mapGroupsToRole(groups []string, roleMap map[string]Role) (Role, bool) {
|
||||
if len(groups) == 0 || len(roleMap) == 0 {
|
||||
return "", false
|
||||
}
|
||||
var (
|
||||
best Role
|
||||
matched bool
|
||||
)
|
||||
for _, g := range groups {
|
||||
role, ok := roleMap[g]
|
||||
if !ok {
|
||||
role, ok = roleMap[strings.TrimSpace(g)]
|
||||
}
|
||||
if !ok || role == "" || role == RoleWorkload || role.Validate() != nil {
|
||||
continue
|
||||
}
|
||||
if !matched || roleRank(role) > roleRank(best) || (roleRank(role) == roleRank(best) && role < best) {
|
||||
best = role
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
return best, matched
|
||||
}
|
||||
|
||||
func roleRank(r Role) int {
|
||||
switch r {
|
||||
case RoleOwner:
|
||||
return 4
|
||||
case RoleAdmin:
|
||||
return 3
|
||||
case RoleDeveloper:
|
||||
return 2
|
||||
case RoleViewer:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"filippo.io/age"
|
||||
gooidc "github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/go-jose/go-jose/v4"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
)
|
||||
|
||||
// TestEnterpriseOIDCConfigValidation guards the configuration boundary for
|
||||
// confidential OIDC, group-to-role mapping, SSO-only mode, and session timeouts.
|
||||
func TestEnterpriseOIDCConfigValidation(t *testing.T) {
|
||||
base := func() AuthenticationSettings {
|
||||
return AuthenticationSettings{
|
||||
PublicURL: "https://archie.example",
|
||||
OIDCIssuer: "https://idp.example",
|
||||
OIDCAudience: "archie",
|
||||
OIDCClientID: "archie-web",
|
||||
}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
edit func(*AuthenticationSettings)
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "valid confidential OIDC with group role map and timeouts",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
s.OIDCClientSecret = "test-client-secret-value" //nolint:gosec // test fixture
|
||||
s.OIDCGroupsClaim = "groups"
|
||||
s.OIDCRoleMap = map[string]Role{"sec-owners": RoleOwner, "ops": RoleAdmin}
|
||||
s.SSOOnly = true
|
||||
s.SessionIdleTimeoutS = 900
|
||||
s.SessionMaxLifetimeS = 28800
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "whitespace-only client secret is refused",
|
||||
edit: func(s *AuthenticationSettings) { s.OIDCClientSecret = " " },
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "client secret without OIDC issuer is refused",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
*s = AuthenticationSettings{
|
||||
PublicURL: "https://archie.example",
|
||||
OIDCClientSecret: "test-client-secret-value", //nolint:gosec // test fixture
|
||||
}
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "sso_only without OIDC issuer is refused",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
*s = AuthenticationSettings{PublicURL: "https://archie.example", SSOOnly: true}
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "role map without groups claim is refused",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
s.OIDCRoleMap = map[string]Role{"ops": RoleAdmin}
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "role map with blank group name is refused",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
s.OIDCGroupsClaim = "groups"
|
||||
s.OIDCRoleMap = map[string]Role{" ": RoleAdmin}
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "role map assigning workload role is refused",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
s.OIDCGroupsClaim = "groups"
|
||||
s.OIDCRoleMap = map[string]Role{"workers": RoleWorkload}
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "role map assigning invalid role is refused",
|
||||
edit: func(s *AuthenticationSettings) {
|
||||
s.OIDCGroupsClaim = "groups"
|
||||
s.OIDCRoleMap = map[string]Role{"ops": Role("Not A Role!")}
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "negative idle timeout is refused",
|
||||
edit: func(s *AuthenticationSettings) { s.SessionIdleTimeoutS = -1 },
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "negative max lifetime is refused",
|
||||
edit: func(s *AuthenticationSettings) { s.SessionMaxLifetimeS = -60 },
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := base()
|
||||
tt.edit(&s)
|
||||
err := s.Validate()
|
||||
if (err == nil) != tt.want {
|
||||
t.Fatalf("Validate() err = %v, want valid=%v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type fakeSyncer struct {
|
||||
org OrgID
|
||||
members []Membership
|
||||
err error
|
||||
ensureErr error
|
||||
}
|
||||
|
||||
func (f *fakeSyncer) OrgForIdentity(context.Context, IdentityID) (OrgID, error) {
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
return f.org, nil
|
||||
}
|
||||
|
||||
func (f *fakeSyncer) EnsureMembership(_ context.Context, m Membership) error {
|
||||
if f.ensureErr != nil {
|
||||
return f.ensureErr
|
||||
}
|
||||
f.members = append(f.members, m)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestGroupClaimRoleMapping guards OIDC group extraction, highest-privilege role
|
||||
// selection, and org membership synchronization during OIDC sign-in.
|
||||
func TestGroupClaimRoleMapping(t *testing.T) {
|
||||
roleMap := map[string]Role{
|
||||
"org-viewers": RoleViewer,
|
||||
"org-devs": RoleDeveloper,
|
||||
"org-admins": RoleAdmin,
|
||||
"org-owners": RoleOwner,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
raw map[string]any
|
||||
claim string
|
||||
wantRole Role
|
||||
wantOK bool
|
||||
}{
|
||||
{
|
||||
name: "string slice selects highest privilege role",
|
||||
raw: map[string]any{"groups": []any{"org-viewers", "org-admins", "unmapped"}},
|
||||
claim: "groups",
|
||||
wantRole: RoleAdmin,
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "single string group claim maps cleanly",
|
||||
raw: map[string]any{"roles": "org-devs"},
|
||||
claim: "roles",
|
||||
wantRole: RoleDeveloper,
|
||||
wantOK: true,
|
||||
},
|
||||
{
|
||||
name: "unmapped groups return false",
|
||||
raw: map[string]any{"groups": []any{"marketing", "finance"}},
|
||||
claim: "groups",
|
||||
wantOK: false,
|
||||
},
|
||||
{
|
||||
name: "missing claim returns false",
|
||||
raw: map[string]any{"sub": "user-1"},
|
||||
claim: "groups",
|
||||
wantOK: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
groups := extractGroupsClaim(tt.raw, tt.claim)
|
||||
gotRole, gotOK := mapGroupsToRole(groups, roleMap)
|
||||
if gotOK != tt.wantOK || gotRole != tt.wantRole {
|
||||
t.Fatalf("mapGroupsToRole(%v) = (%q, %v), want (%q, %v)", groups, gotRole, gotOK, tt.wantRole, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("syncOIDCRole updates org membership", func(t *testing.T) {
|
||||
syncer := &fakeSyncer{org: DefaultOrgID}
|
||||
settings := AuthenticationSettings{OIDCGroupsClaim: "groups", OIDCRoleMap: roleMap}
|
||||
if err := syncOIDCRole(t.Context(), slog.New(slog.DiscardHandler), syncer, "alice", []string{"org-viewers", "org-admins"}, settings); err != nil {
|
||||
t.Fatalf("syncOIDCRole: %v", err)
|
||||
}
|
||||
if len(syncer.members) != 1 || syncer.members[0] != (Membership{IdentityID: "alice", OrgID: DefaultOrgID, Role: RoleAdmin}) {
|
||||
t.Fatalf("synced = %+v, want alice=admin in %s", syncer.members, DefaultOrgID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("syncOIDCRole preserves last owner instead of locking out org", func(t *testing.T) {
|
||||
syncer := &fakeSyncer{org: DefaultOrgID, ensureErr: ErrLastOwner}
|
||||
settings := AuthenticationSettings{OIDCGroupsClaim: "groups", OIDCRoleMap: roleMap}
|
||||
if err := syncOIDCRole(t.Context(), slog.New(slog.DiscardHandler), syncer, "alice", []string{"org-viewers"}, settings); err != nil {
|
||||
t.Fatalf("syncOIDCRole returned %v for ErrLastOwner, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestOIDCConfidentialExchangeAndBackchannelLogout tests confidential OIDC
|
||||
// code exchange with client_secret, ID token group claim extraction, and
|
||||
// back-channel logout JWT verification against an in-process OIDC provider.
|
||||
func TestOIDCConfidentialExchangeAndBackchannelLogout(t *testing.T) {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const (
|
||||
clientID = "archie-enterprise"
|
||||
clientSecret = "super-secret-client-credential" //nolint:gosec // test fixture
|
||||
kid = "key-1"
|
||||
)
|
||||
var (
|
||||
srvURL string
|
||||
nonceToSign string
|
||||
gotSecret string
|
||||
)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.MarshalWrite(w, map[string]any{
|
||||
"issuer": srvURL,
|
||||
"authorization_endpoint": srvURL + "/authorize",
|
||||
"token_endpoint": srvURL + "/token",
|
||||
"jwks_uri": srvURL + "/jwks",
|
||||
"id_token_signing_alg_values_supported": []string{"RS256"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/jwks", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
jwk := jose.JSONWebKey{Key: &priv.PublicKey, KeyID: kid, Algorithm: string(jose.RS256), Use: "sig"}
|
||||
_ = json.MarshalWrite(w, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{jwk}})
|
||||
})
|
||||
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
if user, pass, ok := r.BasicAuth(); ok && user == clientID {
|
||||
gotSecret = pass
|
||||
} else {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
vals, _ := url.ParseQuery(string(body))
|
||||
gotSecret = vals.Get("client_secret")
|
||||
}
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
|
||||
"iss": srvURL,
|
||||
"sub": "oidc-user-42",
|
||||
"aud": clientID,
|
||||
"nonce": nonceToSign,
|
||||
"email": "alice@example.com",
|
||||
"email_verified": true,
|
||||
"groups": []string{"sec-viewers", "sec-admins"},
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
})
|
||||
tok.Header["kid"] = kid
|
||||
rawID, signErr := tok.SignedString(priv)
|
||||
if signErr != nil {
|
||||
http.Error(w, signErr.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.MarshalWrite(w, map[string]any{
|
||||
"access_token": "at-1",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"id_token": rawID,
|
||||
})
|
||||
})
|
||||
srv := httptest.NewTLSServer(mux)
|
||||
defer srv.Close()
|
||||
srvURL = srv.URL
|
||||
|
||||
ctx := gooidc.ClientContext(t.Context(), srv.Client())
|
||||
prov, err := newOIDCProvider(srvURL, clientID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flow, err := newOIDCFlow(prov, clientID, clientSecret, "https://archie.example/oauth2/callback", "groups")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authURL, verifier, err := flow.AuthCodeURL(ctx, "state-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsedAuth, err := url.Parse(authURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nonceToSign = parsedAuth.Query().Get("nonce")
|
||||
|
||||
sess, err := flow.Exchange(ctx, "auth-code-1", verifier)
|
||||
if err != nil {
|
||||
t.Fatalf("Exchange: %v", err)
|
||||
}
|
||||
if gotSecret != clientSecret {
|
||||
t.Fatalf("token endpoint saw client_secret = %q, want %q", gotSecret, clientSecret)
|
||||
}
|
||||
if sess.Credential.Subject != (Subject{Issuer: srvURL, Subject: "oidc-user-42"}) {
|
||||
t.Fatalf("subject = %+v", sess.Credential.Subject)
|
||||
}
|
||||
if len(sess.Credential.Groups) != 2 || sess.Credential.Groups[0] != "sec-viewers" || sess.Credential.Groups[1] != "sec-admins" {
|
||||
t.Fatalf("groups = %v, want [sec-viewers sec-admins]", sess.Credential.Groups)
|
||||
}
|
||||
|
||||
signLogout := func(claims jwt.MapClaims) string {
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
tok.Header["kid"] = kid
|
||||
s, err := tok.SignedString(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
claims jwt.MapClaims
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "valid logout token without exp",
|
||||
claims: jwt.MapClaims{
|
||||
"iss": srvURL,
|
||||
"sub": "oidc-user-42",
|
||||
"aud": clientID,
|
||||
"iat": time.Now().Unix(),
|
||||
"jti": "logout-1",
|
||||
"events": map[string]any{backchannelLogoutEvent: map[string]any{}},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "logout token with nonce is refused",
|
||||
claims: jwt.MapClaims{
|
||||
"iss": srvURL,
|
||||
"sub": "oidc-user-42",
|
||||
"aud": clientID,
|
||||
"nonce": "forbidden",
|
||||
"events": map[string]any{backchannelLogoutEvent: map[string]any{}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "logout token without backchannel-logout event is refused",
|
||||
claims: jwt.MapClaims{
|
||||
"iss": srvURL,
|
||||
"sub": "oidc-user-42",
|
||||
"aud": clientID,
|
||||
"events": map[string]any{"other": map[string]any{}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "expired logout token is refused",
|
||||
claims: jwt.MapClaims{
|
||||
"iss": srvURL,
|
||||
"sub": "oidc-user-42",
|
||||
"aud": clientID,
|
||||
"exp": time.Now().Add(-time.Minute).Unix(),
|
||||
"events": map[string]any{backchannelLogoutEvent: map[string]any{}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
sub, err := flow.VerifyLogoutToken(ctx, signLogout(tt.claims))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("VerifyLogoutToken err = %v, wantErr = %v", err, tt.wantErr)
|
||||
}
|
||||
if !tt.wantErr && sub != (Subject{Issuer: srvURL, Subject: "oidc-user-42"}) {
|
||||
t.Fatalf("subject = %+v", sub)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSOOnlyRefusesNonOwnerPasswordSignIn guards the SSO-only boundary:
|
||||
// non-owners are refused local password sign-in with ErrSSOOnly, while active
|
||||
// org owners retain audited break-glass access.
|
||||
func TestSSOOnlyRefusesNonOwnerPasswordSignIn(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ssoOnly bool
|
||||
isOrgOwner bool
|
||||
wantBreakGlass bool
|
||||
wantErr error
|
||||
}{
|
||||
{name: "standard mode allows non-owner", ssoOnly: false, isOrgOwner: false},
|
||||
{name: "standard mode allows owner without break-glass", ssoOnly: false, isOrgOwner: true},
|
||||
{name: "sso-only refuses non-owner", ssoOnly: true, isOrgOwner: false, wantErr: ErrSSOOnly},
|
||||
{name: "sso-only permits owner break-glass", ssoOnly: true, isOrgOwner: true, wantBreakGlass: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
bg, err := allowPasswordSignIn(tt.ssoOnly, tt.isOrgOwner)
|
||||
if !errors.Is(err, tt.wantErr) || bg != tt.wantBreakGlass {
|
||||
t.Fatalf("allowPasswordSignIn(%v, %v) = (%v, %v), want (%v, %v)", tt.ssoOnly, tt.isOrgOwner, bg, err, tt.wantBreakGlass, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
if !refused(ErrSSOOnly) {
|
||||
t.Fatal("refused(ErrSSOOnly) = false, want true")
|
||||
}
|
||||
m := &Module{log: slog.New(slog.DiscardHandler)}
|
||||
if err := m.accountError(t.Context(), ErrSSOOnly); err == nil || !strings.Contains(err.Error(), "SSO-only") {
|
||||
t.Fatalf("accountError(ErrSSOOnly) = %v, want 403 SSO-only error", err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeSessionStore struct {
|
||||
sessions map[string]store.AccountSessionRow
|
||||
deleted []string
|
||||
touched []time.Time
|
||||
}
|
||||
|
||||
func (f *fakeSessionStore) GetAccountSession(_ context.Context, tokenHash string) (store.AccountSessionRow, error) {
|
||||
s, ok := f.sessions[tokenHash]
|
||||
if !ok {
|
||||
return store.AccountSessionRow{}, store.ErrCredentialRejected
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (f *fakeSessionStore) TouchAccountSession(_ context.Context, tokenHash string, at time.Time) error {
|
||||
s := f.sessions[tokenHash]
|
||||
s.LastSeenAt = at
|
||||
f.sessions[tokenHash] = s
|
||||
f.touched = append(f.touched, at)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSessionStore) DeleteAccountSession(_ context.Context, tokenHash string) error {
|
||||
delete(f.sessions, tokenHash)
|
||||
f.deleted = append(f.deleted, tokenHash)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestSessionIdleAndMaxLifetimeExpiry guards sliding idle timeouts and absolute
|
||||
// max session lifetimes during session resolution.
|
||||
func TestSessionIdleAndMaxLifetimeExpiry(t *testing.T) {
|
||||
base := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC)
|
||||
if got := sessionExpiry(base, 3600); !got.Equal(base.Add(time.Hour)) {
|
||||
t.Fatalf("sessionExpiry(3600) = %v, want %v", got, base.Add(time.Hour))
|
||||
}
|
||||
if got := sessionExpiry(base, 0); !got.Equal(base.Add(AccountSessionLifetime)) {
|
||||
t.Fatalf("sessionExpiry(0) = %v, want %v", got, base.Add(AccountSessionLifetime))
|
||||
}
|
||||
|
||||
makeRow := func(issued, lastSeen, expires time.Time) store.AccountSessionRow {
|
||||
return store.AccountSessionRow{
|
||||
ID: "alice", Kind: "user", Lifecycle: "active",
|
||||
IssuedAt: issued,
|
||||
LastSeenAt: lastSeen,
|
||||
ExpiresAt: expires,
|
||||
}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
row store.AccountSessionRow
|
||||
idleS int
|
||||
maxS int
|
||||
now time.Time
|
||||
wantErr error
|
||||
wantDel bool
|
||||
wantTouch bool
|
||||
}{
|
||||
{
|
||||
name: "active session refreshes last_seen_at",
|
||||
row: makeRow(base, base.Add(5*time.Minute), base.Add(time.Hour)),
|
||||
idleS: 600,
|
||||
maxS: 3600,
|
||||
now: base.Add(10 * time.Minute),
|
||||
wantTouch: true,
|
||||
},
|
||||
{
|
||||
name: "idle timeout expires session even before max lifetime",
|
||||
row: makeRow(base, base, base.Add(time.Hour)),
|
||||
idleS: 600,
|
||||
maxS: 3600,
|
||||
now: base.Add(10 * time.Minute),
|
||||
wantErr: ErrCredentialRejected,
|
||||
wantDel: true,
|
||||
},
|
||||
{
|
||||
name: "max lifetime expires active session even with recent activity",
|
||||
row: makeRow(base, base.Add(59*time.Minute), base.Add(24*time.Hour)),
|
||||
idleS: 600,
|
||||
maxS: 3600,
|
||||
now: base.Add(time.Hour),
|
||||
wantErr: ErrCredentialRejected,
|
||||
wantDel: true,
|
||||
},
|
||||
{
|
||||
name: "hard expires_at still rejects when max_lifetime_s is zero",
|
||||
row: makeRow(base, base, base.Add(30*time.Minute)),
|
||||
now: base.Add(30 * time.Minute),
|
||||
wantErr: ErrCredentialRejected,
|
||||
wantDel: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
fs := &fakeSessionStore{sessions: map[string]store.AccountSessionRow{"tok": tt.row}}
|
||||
id, err := resolveAccountSession(t.Context(), fs, "tok", tt.idleS, tt.maxS, tt.now)
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
if tt.wantDel && len(fs.deleted) != 1 {
|
||||
t.Fatalf("deleted = %v, want session removed", fs.deleted)
|
||||
}
|
||||
if tt.wantTouch && (len(fs.touched) != 1 || !fs.touched[0].Equal(tt.now) || id.ID != "alice") {
|
||||
t.Fatalf("touched = %v id = %q, want %v and alice", fs.touched, id.ID, tt.now)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSealerProtectsOIDCClientSecret guards sealing and label binding for the
|
||||
// OIDC client secret in governance settings.
|
||||
func TestSealerProtectsOIDCClientSecret(t *testing.T) {
|
||||
ageID, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealer, err := seal.New(ageID.String(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := &Module{sealer: sealer}
|
||||
sealed, err := m.sealOIDCSecret("https://idp.example", "client-secret-123")
|
||||
if err != nil {
|
||||
t.Fatalf("sealOIDCSecret: %v", err)
|
||||
}
|
||||
plain, err := sealer.Open(oidcSecretLabel, sealed)
|
||||
if err != nil || string(plain) != "client-secret-123" {
|
||||
t.Fatalf("Open = (%q, %v), want client-secret-123", plain, err)
|
||||
}
|
||||
if _, err := sealer.Open("wrong-label", sealed); !errors.Is(err, seal.ErrWrongLabel) {
|
||||
t.Fatalf("Open(wrong-label) = %v, want ErrWrongLabel", err)
|
||||
}
|
||||
}
|
||||
@@ -435,32 +435,108 @@ func registrationScope(ctx context.Context, r *AccountRegistration, bootstrap bo
|
||||
}
|
||||
|
||||
// SignInAccount verifies email and password and opens a session.
|
||||
// When sso_only is enabled, non-owner accounts are refused with ErrSSOOnly;
|
||||
// active organisation owners retain break-glass local sign-in with an audit log.
|
||||
func (m *Module) SignInAccount(ctx context.Context, email, password string) (AccountSession, error) {
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return AccountSession{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
token := rand.Text()
|
||||
expires := time.Now().UTC().Add(AccountSessionLifetime)
|
||||
expires := sessionExpiry(now, settings.SessionMaxLifetimeS)
|
||||
var breakGlassID string
|
||||
row, err := m.store.SignInAccount(ctx, email, sessionHash(token), expires, func(hash string) bool {
|
||||
if hash == "" {
|
||||
_, _ = HashPassword("unknown account dummy password")
|
||||
return false
|
||||
}
|
||||
return VerifyPassword(password, hash)
|
||||
}, func(identityID string, isOrgOwner bool) error {
|
||||
breakGlass, err := allowPasswordSignIn(settings.SSOOnly, isOrgOwner)
|
||||
if err != nil {
|
||||
m.log.WarnContext(ctx, "password sign-in refused: sso_only enabled", "audit", true, "identity", identityID)
|
||||
return err
|
||||
}
|
||||
if breakGlass {
|
||||
breakGlassID = identityID
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return AccountSession{}, mapIdentityErr(err)
|
||||
}
|
||||
if breakGlassID != "" {
|
||||
m.log.WarnContext(ctx, "break-glass local password sign-in used while sso_only is enabled", "audit", true, "identity", breakGlassID)
|
||||
}
|
||||
return AccountSession{Identity: identityFromRow(row), Token: token, Expires: expires}, nil
|
||||
}
|
||||
|
||||
// ResolveAccountSession resolves a session token to its active identity.
|
||||
func allowPasswordSignIn(ssoOnly, isOrgOwner bool) (breakGlass bool, err error) {
|
||||
if !ssoOnly {
|
||||
return false, nil
|
||||
}
|
||||
if isOrgOwner {
|
||||
return true, nil
|
||||
}
|
||||
return false, ErrSSOOnly
|
||||
}
|
||||
|
||||
func sessionExpiry(now time.Time, maxLifetimeS int) time.Time {
|
||||
if maxLifetimeS > 0 {
|
||||
return now.Add(time.Duration(maxLifetimeS) * time.Second)
|
||||
}
|
||||
return now.Add(AccountSessionLifetime)
|
||||
}
|
||||
|
||||
func checkSessionTimeouts(now, issuedAt, lastSeenAt, expiresAt time.Time, idleTimeoutS, maxLifetimeS int) error {
|
||||
if !now.Before(expiresAt) {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
if maxLifetimeS > 0 && !now.Before(issuedAt.Add(time.Duration(maxLifetimeS)*time.Second)) {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
if idleTimeoutS > 0 && !now.Before(lastSeenAt.Add(time.Duration(idleTimeoutS)*time.Second)) {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type accountSessionStore interface {
|
||||
GetAccountSession(ctx context.Context, tokenHash string) (store.AccountSessionRow, error)
|
||||
TouchAccountSession(ctx context.Context, tokenHash string, at time.Time) error
|
||||
DeleteAccountSession(ctx context.Context, tokenHash string) error
|
||||
}
|
||||
|
||||
func resolveAccountSession(ctx context.Context, sessStore accountSessionStore, tokenHash string, idleTimeoutS, maxLifetimeS int, now time.Time) (Identity, error) {
|
||||
row, err := sessStore.GetAccountSession(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return Identity{}, mapIdentityErr(err)
|
||||
}
|
||||
if row.Lifecycle != string(LifecycleActive) {
|
||||
return Identity{}, ErrCredentialRejected
|
||||
}
|
||||
if err := checkSessionTimeouts(now, row.IssuedAt, row.LastSeenAt, row.ExpiresAt, idleTimeoutS, maxLifetimeS); err != nil {
|
||||
_ = sessStore.DeleteAccountSession(ctx, tokenHash)
|
||||
return Identity{}, err
|
||||
}
|
||||
if err := sessStore.TouchAccountSession(ctx, tokenHash, now); err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
return identityFromRow(row.IdentityRow), nil
|
||||
}
|
||||
|
||||
// ResolveAccountSession resolves a session token to its active identity,
|
||||
// enforcing idle timeout and max lifetime and refreshing last_seen_at.
|
||||
func (m *Module) ResolveAccountSession(ctx context.Context, token string) (Identity, error) {
|
||||
if len(token) < 26 || len(token) > 128 {
|
||||
return Identity{}, ErrCredentialRejected
|
||||
}
|
||||
row, err := m.store.ResolveAccountSession(ctx, sessionHash(token))
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return Identity{}, mapIdentityErr(err)
|
||||
return Identity{}, err
|
||||
}
|
||||
return identityFromRow(row), nil
|
||||
return resolveAccountSession(ctx, m.store, sessionHash(token), settings.SessionIdleTimeoutS, settings.SessionMaxLifetimeS, time.Now().UTC())
|
||||
}
|
||||
|
||||
// SignOutAccount deletes the session associated with token.
|
||||
@@ -468,6 +544,21 @@ func (m *Module) SignOutAccount(ctx context.Context, token string) error {
|
||||
return m.store.DeleteAccountSession(ctx, sessionHash(token))
|
||||
}
|
||||
|
||||
// RevokeSessionsBySubject deletes every active session belonging to the
|
||||
// identity bound to (issuer, subject).
|
||||
func (m *Module) RevokeSessionsBySubject(ctx context.Context, issuer, subject string) error {
|
||||
issuer, subject = strings.TrimSpace(issuer), strings.TrimSpace(subject)
|
||||
if issuer == "" || subject == "" {
|
||||
return ErrInvalidIdentity
|
||||
}
|
||||
n, err := m.store.RevokeSessionsBySubject(ctx, issuer, subject)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.log.InfoContext(ctx, "revoked sessions for provider subject", "issuer", issuer, "subject", subject, "revoked", n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ChangeAccountPassword verifies current, sets next, and revokes active sessions.
|
||||
func (m *Module) ChangeAccountPassword(ctx context.Context, current, next string) error {
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
@@ -483,16 +574,21 @@ func (m *Module) ChangeAccountPassword(ctx context.Context, current, next string
|
||||
}, hash))
|
||||
}
|
||||
|
||||
// OpenAccountSession creates a session bounded by expires for the current principal.
|
||||
// OpenAccountSession creates a session bounded by expires and session_max_lifetime_s for the current principal.
|
||||
func (m *Module) OpenAccountSession(ctx context.Context, expires time.Time) (AccountSession, error) {
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return AccountSession{}, ErrCredentialRejected
|
||||
}
|
||||
if expires.IsZero() || !expires.After(time.Now()) {
|
||||
now := time.Now().UTC()
|
||||
if expires.IsZero() || !expires.After(now) {
|
||||
return AccountSession{}, ErrCredentialRejected
|
||||
}
|
||||
maxExpires := time.Now().UTC().Add(AccountSessionLifetime)
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return AccountSession{}, err
|
||||
}
|
||||
maxExpires := sessionExpiry(now, settings.SessionMaxLifetimeS)
|
||||
if maxExpires.Before(expires) {
|
||||
expires = maxExpires
|
||||
}
|
||||
@@ -504,17 +600,29 @@ func (m *Module) OpenAccountSession(ctx context.Context, expires time.Time) (Acc
|
||||
return AccountSession{Identity: identityFromRow(row), Token: token, Expires: expires}, nil
|
||||
}
|
||||
|
||||
// RequireFreshAccountSession requires token to have been issued within the last 10 minutes.
|
||||
// RequireFreshAccountSession requires token to have been issued within the last 10 minutes
|
||||
// and still valid under idle/max session limits.
|
||||
func (m *Module) RequireFreshAccountSession(ctx context.Context, token string) error {
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
fresh, err := m.store.IsFreshAccountSession(ctx, string(p.IdentityID), sessionHash(token))
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fresh {
|
||||
now := time.Now().UTC()
|
||||
row, err := m.store.GetAccountSession(ctx, sessionHash(token))
|
||||
if err != nil {
|
||||
return mapIdentityErr(err)
|
||||
}
|
||||
if row.ID != string(p.IdentityID) || row.Lifecycle != string(LifecycleActive) {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
if err := checkSessionTimeouts(now, row.IssuedAt, row.LastSeenAt, row.ExpiresAt, settings.SessionIdleTimeoutS, settings.SessionMaxLifetimeS); err != nil {
|
||||
return err
|
||||
}
|
||||
if !now.Before(row.IssuedAt.Add(10 * time.Minute)) {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
return nil
|
||||
@@ -545,7 +653,10 @@ func (m *Module) RecoverAccount(ctx context.Context, email, code, password strin
|
||||
return mapIdentityErr(m.store.RecoverAccount(ctx, email, sessionHash(code), hash))
|
||||
}
|
||||
|
||||
// AuthenticationSettings returns the instance authentication settings.
|
||||
const oidcSecretLabel = "governance:authentication_settings:oidc_client_secret"
|
||||
|
||||
// AuthenticationSettings returns the instance authentication settings without
|
||||
// exposing any stored client secret.
|
||||
func (m *Module) AuthenticationSettings(ctx context.Context) (AuthenticationSettings, error) {
|
||||
row, err := m.store.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
@@ -555,15 +666,43 @@ func (m *Module) AuthenticationSettings(ctx context.Context) (AuthenticationSett
|
||||
if err != nil {
|
||||
return AuthenticationSettings{}, err
|
||||
}
|
||||
roleMap, err := decodeRoleMap(row.OIDCRoleMap)
|
||||
if err != nil {
|
||||
return AuthenticationSettings{}, err
|
||||
}
|
||||
return AuthenticationSettings{
|
||||
PublicURL: row.PublicURL,
|
||||
TrustedProxies: proxies,
|
||||
OIDCIssuer: row.OIDCIssuer,
|
||||
OIDCAudience: row.OIDCAudience,
|
||||
OIDCClientID: row.OIDCClientID,
|
||||
PublicURL: row.PublicURL,
|
||||
TrustedProxies: proxies,
|
||||
OIDCIssuer: row.OIDCIssuer,
|
||||
OIDCAudience: row.OIDCAudience,
|
||||
OIDCClientID: row.OIDCClientID,
|
||||
OIDCClientSecretSet: len(row.OIDCClientSecretSealed) > 0,
|
||||
OIDCGroupsClaim: row.OIDCGroupsClaim,
|
||||
OIDCRoleMap: roleMap,
|
||||
SSOOnly: row.SSOOnly,
|
||||
SessionIdleTimeoutS: row.SessionIdleTimeoutS,
|
||||
SessionMaxLifetimeS: row.SessionMaxLifetimeS,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *Module) oidcClientSecret(ctx context.Context) (string, error) {
|
||||
row, err := m.store.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(row.OIDCClientSecretSealed) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
if m.sealer == nil {
|
||||
return "", errors.New("sealer is required to open OIDC client secret")
|
||||
}
|
||||
plain, err := m.sealer.Open(oidcSecretLabel, row.OIDCClientSecretSealed)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open OIDC client secret: %w", err)
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
// SaveAuthenticationSettings validates and persists instance authentication settings.
|
||||
func (m *Module) SaveAuthenticationSettings(ctx context.Context, value AuthenticationSettings) error {
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
@@ -571,6 +710,7 @@ func (m *Module) SaveAuthenticationSettings(ctx context.Context, value Authentic
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
value.PublicURL = strings.TrimRight(value.PublicURL, "/")
|
||||
value.OIDCGroupsClaim = strings.TrimSpace(value.OIDCGroupsClaim)
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -582,12 +722,26 @@ func (m *Module) SaveAuthenticationSettings(ctx context.Context, value Authentic
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
roleMapJSON, err := encodeRoleMap(value.OIDCRoleMap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sealedSecret, err := m.sealOIDCSecret(value.OIDCIssuer, value.OIDCClientSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updated, err := m.store.SaveAuthenticationSettings(ctx, store.AuthSettingsRow{
|
||||
PublicURL: value.PublicURL,
|
||||
TrustedProxies: encoded,
|
||||
OIDCIssuer: value.OIDCIssuer,
|
||||
OIDCAudience: value.OIDCAudience,
|
||||
OIDCClientID: value.OIDCClientID,
|
||||
PublicURL: value.PublicURL,
|
||||
TrustedProxies: encoded,
|
||||
OIDCIssuer: value.OIDCIssuer,
|
||||
OIDCAudience: value.OIDCAudience,
|
||||
OIDCClientID: value.OIDCClientID,
|
||||
OIDCClientSecretSealed: sealedSecret,
|
||||
OIDCGroupsClaim: value.OIDCGroupsClaim,
|
||||
OIDCRoleMap: roleMapJSON,
|
||||
SSOOnly: value.SSOOnly,
|
||||
SessionIdleTimeoutS: value.SessionIdleTimeoutS,
|
||||
SessionMaxLifetimeS: value.SessionMaxLifetimeS,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -598,6 +752,44 @@ func (m *Module) SaveAuthenticationSettings(ctx context.Context, value Authentic
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Module) sealOIDCSecret(issuer, secret string) ([]byte, error) {
|
||||
if issuer == "" {
|
||||
return []byte{}, nil
|
||||
}
|
||||
if secret == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if m.sealer == nil {
|
||||
return nil, errors.New("sealer is required to store OIDC client secret")
|
||||
}
|
||||
sealed, err := m.sealer.Seal(oidcSecretLabel, []byte(secret))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seal OIDC client secret: %w", err)
|
||||
}
|
||||
return sealed, nil
|
||||
}
|
||||
|
||||
func encodeRoleMap(roleMap map[string]Role) ([]byte, error) {
|
||||
if len(roleMap) == 0 {
|
||||
return []byte("{}"), nil
|
||||
}
|
||||
return json.Marshal(roleMap)
|
||||
}
|
||||
|
||||
func decodeRoleMap(raw []byte) (map[string]Role, error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var out map[string]Role
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("read OIDC role map: %w", err)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type passkeyUser struct {
|
||||
value Identity
|
||||
credentials []webauthn.Credential
|
||||
@@ -690,6 +882,10 @@ func (m *Module) BeginPasskey(ctx context.Context, registration bool) (PasskeyCe
|
||||
|
||||
// FinishPasskey completes a WebAuthn passkey ceremony and issues a session on sign-in.
|
||||
func (m *Module) FinishPasskey(ctx context.Context, token string, response []byte, registration bool, name string) (AccountSession, error) {
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return AccountSession{}, err
|
||||
}
|
||||
wa, err := m.webAuthn(ctx)
|
||||
if err != nil {
|
||||
return AccountSession{}, err
|
||||
@@ -714,7 +910,7 @@ func (m *Module) FinishPasskey(ctx context.Context, token string, response []byt
|
||||
result = AccountSession{Identity: user.value}
|
||||
if !registration {
|
||||
result.Token = rand.Text()
|
||||
result.Expires = time.Now().UTC().Add(AccountSessionLifetime)
|
||||
result.Expires = sessionExpiry(time.Now().UTC(), settings.SessionMaxLifetimeS)
|
||||
return pt.InsertSession(ctx, sessionHash(result.Token), string(user.value.ID), result.Expires)
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in new issue
Block a user