feat: implement package and cli tool for repairing oidc links (#26418)

This commit is contained in:
Steven Masley
2026-06-16 12:46:10 -07:00
committed by GitHub
parent b71bc31eec
commit 1d03e63f4f
19 changed files with 1116 additions and 1 deletions
+2 -1
View File
@@ -1427,6 +1427,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
createAdminUserCmd := r.newCreateAdminUserCommand()
regenerateVapidKeypairCmd := r.newRegenerateVapidKeypairCommand()
fixOIDCLinksCmd := r.newFixOIDCLinksCommand()
rawURLOpt := serpent.Option{
Flag: "raw-url",
@@ -1440,7 +1441,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
serverCmd.Children = append(
serverCmd.Children,
createAdminUserCmd, postgresBuiltinURLCmd, postgresBuiltinServeCmd, regenerateVapidKeypairCmd,
createAdminUserCmd, postgresBuiltinURLCmd, postgresBuiltinServeCmd, regenerateVapidKeypairCmd, fixOIDCLinksCmd,
)
return serverCmd
+156
View File
@@ -0,0 +1,156 @@
//go:build !slim
package cli
import (
"fmt"
"net/http"
"strings"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/sloghuman"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/authlink"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/awsiamrds"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (r *RootCmd) newFixOIDCLinksCommand() *serpent.Command {
var (
pgURL string
pgAuth string
issuerURL string
dryRun bool
)
fixOIDCLinksCmd := &serpent.Command{
Use: "fix-oidc-links",
Short: "Reset OIDC linked IDs that do not match the expected issuer, allowing users to re-authenticate.",
Handler: func(inv *serpent.Invocation) error {
var (
ctx, cancel = inv.SignalNotifyContext(inv.Context(), StopSignals...)
logger = inv.Logger.AppendSinks(sloghuman.Sink(inv.Stderr))
)
if r.verbose {
logger = logger.Leveled(slog.LevelDebug)
}
defer cancel()
issuerURL = strings.TrimSpace(issuerURL)
if issuerURL == "" {
return xerrors.Errorf("the --%s flag is required, set it to the OIDC issuer URL (e.g. https://accounts.google.com)", "issuer-url")
}
// Resolve the canonical issuer from OIDC discovery.
cliui.Infof(inv.Stdout, "Resolving OIDC issuer from %q...", issuerURL)
// TODO: The default client might not be configured with the right certs to make this request.
issuer, err := authlink.ResolveIssuer(ctx, http.DefaultClient, issuerURL)
if err != nil {
return xerrors.Errorf("resolve issuer: %w", err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Resolved OIDC issuer: %q\n\n", issuer)
// Connect to the database.
if pgURL == "" {
return xerrors.New("the --postgres-url flag is required")
}
sqlDriver := "postgres"
if codersdk.PostgresAuth(pgAuth) == codersdk.PostgresAuthAWSIAMRDS {
sqlDriver, err = awsiamrds.Register(inv.Context(), sqlDriver)
if err != nil {
return xerrors.Errorf("register aws rds iam auth: %w", err)
}
}
sqlDB, err := ConnectToPostgres(ctx, logger, sqlDriver, pgURL, nil)
if err != nil {
return xerrors.Errorf("connect to postgres: %w", err)
}
defer func() {
_ = sqlDB.Close()
}()
db := database.New(sqlDB)
// Run analysis.
analysis, err := authlink.AnalyzeOIDCLinks(ctx, db, issuer)
if err != nil {
return xerrors.Errorf("analyze OIDC links: %w", err)
}
authlink.PrintAnalysis(inv.Stdout, analysis, issuer)
_, _ = fmt.Fprintln(inv.Stdout)
if dryRun {
return nil
}
mismatchedTotal := analysis.MismatchedTotal()
if mismatchedTotal == 0 {
_, _ = fmt.Fprintln(inv.Stdout, "Nothing to do. All OIDC links match the expected issuer.")
return nil
}
// Molly guard.
_, _ = fmt.Fprintf(inv.Stdout, "This will reset %d linked IDs to allow affected users to re-authenticate.\n", mismatchedTotal)
if _, err := cliui.Prompt(inv, cliui.PromptOptions{
Text: "Are you sure you want to continue?",
IsConfirm: true,
Default: cliui.ConfirmNo,
}); err != nil {
return err
}
_, _ = fmt.Fprintln(inv.Stdout)
// Execute the reset.
count, err := authlink.ResetMismatchedOIDCLinks(ctx, db, issuer)
if err != nil {
return xerrors.Errorf("reset mismatched OIDC links: %w", err)
}
cliui.Infof(inv.Stdout, "Reset %d linked IDs.", count)
_, _ = fmt.Fprintln(inv.Stdout)
// Print updated analysis.
analysis, err = authlink.AnalyzeOIDCLinks(ctx, db, issuer)
if err != nil {
return xerrors.Errorf("re-analyze OIDC links: %w", err)
}
authlink.PrintAnalysis(inv.Stdout, analysis, issuer)
return nil
},
}
fixOIDCLinksCmd.Options.Add(
cliui.SkipPromptOption(),
serpent.Option{
Env: "CODER_PG_CONNECTION_URL",
Flag: "postgres-url",
Description: "URL of a PostgreSQL database. If empty, the built-in PostgreSQL deployment will be used (Coder must not be already running in this case).",
Value: serpent.StringOf(&pgURL),
},
serpent.Option{
Name: "Postgres Connection Auth",
Description: "Type of auth to use when connecting to postgres.",
Flag: "postgres-connection-auth",
Env: "CODER_PG_CONNECTION_AUTH",
Default: "password",
Value: serpent.EnumOf(&pgAuth, codersdk.PostgresAuthDrivers...),
},
serpent.Option{
Env: "CODER_OIDC_ISSUER_URL",
Flag: "issuer-url",
Description: "The OIDC issuer URL. The canonical issuer is resolved via OIDC discovery.",
Value: serpent.StringOf(&issuerURL),
},
serpent.Option{
Flag: "dry-run",
FlagShorthand: "n",
Env: "CODER_FIX_OIDC_LINKS_DRY_RUN",
Description: "Print analysis only, do not modify the database.",
Value: serpent.BoolOf(&dryRun),
},
)
return fixOIDCLinksCmd
}
+203
View File
@@ -0,0 +1,203 @@
package cli_test
import (
"context"
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/testutil"
"github.com/coder/coder/v2/testutil/expecter"
)
// fakeOIDCDiscovery returns a test server serving an OIDC discovery document.
func fakeOIDCDiscovery(t *testing.T, issuer string) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/.well-known/openid-configuration" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"issuer": issuer,
})
}))
t.Cleanup(srv.Close)
return srv
}
func TestFixOIDCLinks(t *testing.T) {
t.Parallel()
t.Run("DryRun", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitMedium)
t.Cleanup(cancel)
const expectedIssuer = "https://accounts.google.com"
oidcSrv := fakeOIDCDiscovery(t, expectedIssuer)
connectionURL, err := dbtestutil.Open(t)
require.NoError(t, err)
sqlDB, err := sql.Open("postgres", connectionURL)
require.NoError(t, err)
defer sqlDB.Close()
db := database.New(sqlDB)
// Seed a correctly linked user.
correctUser := dbgen.User(t, db, database.User{LoginType: database.LoginTypeOIDC})
dbgen.UserLink(t, db, database.UserLink{
UserID: correctUser.ID,
LoginType: database.LoginTypeOIDC,
LinkedID: expectedIssuer + "||sub-correct",
})
// Seed a mismatched user.
mismatchedUser := dbgen.User(t, db, database.User{LoginType: database.LoginTypeOIDC})
dbgen.UserLink(t, db, database.UserLink{
UserID: mismatchedUser.ID,
LoginType: database.LoginTypeOIDC,
LinkedID: "https://old-issuer.example.com||sub-mismatched",
})
inv, _ := clitest.New(t,
"server", "fix-oidc-links",
"--postgres-url", connectionURL,
"--issuer-url", oidcSrv.URL,
"--dry-run",
)
stdout := expecter.NewAttachedToInvocation(t, inv)
w := clitest.StartWithWaiter(t, inv)
stdout.ExpectMatch(ctx, "Resolved OIDC issuer: \""+expectedIssuer+"\"")
stdout.ExpectMatch(ctx, "Total OIDC users:")
stdout.ExpectMatch(ctx, "Correctly linked:")
stdout.ExpectMatch(ctx, "Linked to other issuers:")
w.RequireSuccess()
// Verify no changes were made.
link, err := db.GetUserLinkByUserIDLoginType(ctx, database.GetUserLinkByUserIDLoginTypeParams{
UserID: mismatchedUser.ID,
LoginType: database.LoginTypeOIDC,
})
require.NoError(t, err)
require.Equal(t, "https://old-issuer.example.com||sub-mismatched", link.LinkedID, "dry-run must not modify the database")
})
t.Run("Confirm", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitMedium)
t.Cleanup(cancel)
const expectedIssuer = "https://accounts.google.com"
oidcSrv := fakeOIDCDiscovery(t, expectedIssuer)
connectionURL, err := dbtestutil.Open(t)
require.NoError(t, err)
sqlDB, err := sql.Open("postgres", connectionURL)
require.NoError(t, err)
defer sqlDB.Close()
db := database.New(sqlDB)
// Seed a correctly linked user.
correctUser := dbgen.User(t, db, database.User{LoginType: database.LoginTypeOIDC})
dbgen.UserLink(t, db, database.UserLink{
UserID: correctUser.ID,
LoginType: database.LoginTypeOIDC,
LinkedID: expectedIssuer + "||sub-correct",
})
// Seed mismatched users.
mismatchedUser := dbgen.User(t, db, database.User{LoginType: database.LoginTypeOIDC})
dbgen.UserLink(t, db, database.UserLink{
UserID: mismatchedUser.ID,
LoginType: database.LoginTypeOIDC,
LinkedID: "https://old-issuer.example.com||sub-mismatched",
})
inv, _ := clitest.New(t,
"server", "fix-oidc-links",
"--postgres-url", connectionURL,
"--issuer-url", oidcSrv.URL,
"--yes",
)
stdout := expecter.NewAttachedToInvocation(t, inv)
w := clitest.StartWithWaiter(t, inv)
stdout.ExpectMatch(ctx, "Reset 1 linked IDs.")
w.RequireSuccess()
// Verify the mismatched link was reset.
link, err := db.GetUserLinkByUserIDLoginType(ctx, database.GetUserLinkByUserIDLoginTypeParams{
UserID: mismatchedUser.ID,
LoginType: database.LoginTypeOIDC,
})
require.NoError(t, err)
require.Equal(t, "", link.LinkedID)
// Verify the correct link is unchanged.
link, err = db.GetUserLinkByUserIDLoginType(ctx, database.GetUserLinkByUserIDLoginTypeParams{
UserID: correctUser.ID,
LoginType: database.LoginTypeOIDC,
})
require.NoError(t, err)
require.Equal(t, expectedIssuer+"||sub-correct", link.LinkedID)
})
t.Run("NothingToDo", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitMedium)
t.Cleanup(cancel)
const expectedIssuer = "https://accounts.google.com"
oidcSrv := fakeOIDCDiscovery(t, expectedIssuer)
connectionURL, err := dbtestutil.Open(t)
require.NoError(t, err)
sqlDB, err := sql.Open("postgres", connectionURL)
require.NoError(t, err)
defer sqlDB.Close()
db := database.New(sqlDB)
// All users correctly linked.
user := dbgen.User(t, db, database.User{LoginType: database.LoginTypeOIDC})
dbgen.UserLink(t, db, database.UserLink{
UserID: user.ID,
LoginType: database.LoginTypeOIDC,
LinkedID: expectedIssuer + "||sub-correct",
})
inv, _ := clitest.New(t,
"server", "fix-oidc-links",
"--postgres-url", connectionURL,
"--issuer-url", oidcSrv.URL,
"--yes",
)
stdout := expecter.NewAttachedToInvocation(t, inv)
w := clitest.StartWithWaiter(t, inv)
stdout.ExpectMatch(ctx, "Nothing to do")
w.RequireSuccess()
})
}
+3
View File
@@ -9,6 +9,9 @@ SUBCOMMANDS:
create-admin-user Create a new admin user with the given username,
email and password and adds it to every
organization.
fix-oidc-links Reset OIDC linked IDs that do not match the
expected issuer, allowing users to
re-authenticate.
postgres-builtin-serve Run the built-in PostgreSQL deployment.
postgres-builtin-url Output the connection URL for the built-in
PostgreSQL deployment.
+29
View File
@@ -0,0 +1,29 @@
coder v0.0.0-devel
USAGE:
coder server fix-oidc-links [flags]
Reset OIDC linked IDs that do not match the expected issuer, allowing users to
re-authenticate.
OPTIONS:
--postgres-connection-auth password|awsiamrds, $CODER_PG_CONNECTION_AUTH (default: password)
Type of auth to use when connecting to postgres.
-n, --dry-run bool, $CODER_FIX_OIDC_LINKS_DRY_RUN
Print analysis only, do not modify the database.
--issuer-url string, $CODER_OIDC_ISSUER_URL
The OIDC issuer URL. The canonical issuer is resolved via OIDC
discovery.
--postgres-url string, $CODER_PG_CONNECTION_URL
URL of a PostgreSQL database. If empty, the built-in PostgreSQL
deployment will be used (Coder must not be already running in this
case).
-y, --yes bool
Bypass confirmation prompts.
———
Run `coder --help` for a list of global options.