language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Go
hydra/cmd/serve_all.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/hydra/v2/driver" "github.com/ory/x/configx" "github.com/ory/x/servicelocatorx" "github.com/ory/hydra/v2/cmd/server" ) // allCmd represents the all command func NewServeAllCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { return &cobra.Command{ Use: "all", Short: "Serves both public and administrative HTTP/2 APIs", Long: `Starts a process which listens on two ports for public and administrative HTTP/2 API requests. If you want more granular control (e.g. different TLS settings) over each API group (administrative, public) you can run "serve admin" and "serve public" separately. This command exposes a variety of controls via environment variables. You can set environments using "export KEY=VALUE" (Linux/macOS) or "set KEY=VALUE" (Windows). On Linux, you can also set environments by prepending key value pairs: "KEY=VALUE KEY2=VALUE2 hydra" All possible controls are listed below. This command exposes exposes command line flags, which are listed below the controls section. ` + serveControls, RunE: server.RunServeAll(slOpts, dOpts, cOpts), } }
Go
hydra/cmd/serve_public.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/hydra/v2/driver" "github.com/ory/x/configx" "github.com/ory/x/servicelocatorx" "github.com/ory/hydra/v2/cmd/server" ) // servePublicCmd represents the public command func NewServePublicCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { return &cobra.Command{ Use: "public", Short: "Serves Public HTTP/2 APIs", Long: `This command opens one port and listens to HTTP/2 API requests. The exposed API handles requests coming from the public internet, like OAuth 2.0 Authorization and Token requests, OpenID Connect UserInfo, OAuth 2.0 Token Revokation, and OpenID Connect Discovery. This command is configurable using the same options available to "serve admin" and "serve all". It is generally recommended to use this command only if you require granular control over the privileged and public APIs. For example, you might want to run different TLS certificates or CORS settings on the public and privileged API. This command does not work with the "memory" database. Both services (privileged, public) MUST use the same database connection to be able to synchronize. ` + serveControls, RunE: server.RunServePublic(slOpts, dOpts, cOpts), } }
Go
hydra/cmd/version.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "github.com/ory/hydra/v2/driver/config" "github.com/spf13/cobra" ) // versionCmd represents the version command func NewVersionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Display this binary's version, build time and git hash of this build", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Version: %s\n", config.Version) fmt.Printf("Git Hash: %s\n", config.Commit) fmt.Printf("Build Time: %s\n", config.Date) }, } }
JSON
hydra/cmd/.snapshots/TestCreateClient-case=creates_successfully.json
{ "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "grant_types": [ "authorization_code" ], "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "request_object_signing_alg": "RS256", "response_types": [ "code" ], "scope": "offline_access offline openid", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }
JSON
hydra/cmd/.snapshots/TestCreateClient-case=supports_encryption.json
{ "audience": [ "https://www.ory.sh/audience1", "https://www.ory.sh/audience2" ], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "grant_types": [ "authorization_code" ], "jwks": {}, "logo_uri": "", "metadata": { "foo": "bar" }, "owner": "", "policy_uri": "", "request_object_signing_alg": "RS256", "response_types": [ "code" ], "scope": "offline_access offline openid", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }
JSON
hydra/cmd/.snapshots/TestCreateClient-case=supports_setting_flags.json
{ "audience": [ "https://www.ory.sh/audience1", "https://www.ory.sh/audience2" ], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "grant_types": [ "authorization_code" ], "jwks": {}, "logo_uri": "", "metadata": { "foo": "bar" }, "owner": "", "policy_uri": "", "request_object_signing_alg": "RS256", "response_types": [ "code" ], "scope": "offline_access offline openid", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }
JSON
hydra/cmd/.snapshots/TestDeleteClient-case=one_client_deletion_fails.json
"{\n \"error\": \"Unable to locate the resource\",\n \"error_description\": \"\"\n}\nFailed to execute API request, see error above.\ni-do-not-exist: this error should never be printed\n"
JSON
hydra/cmd/.snapshots/TestGetClient-case=gets_client.json
{ "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "scope": "", "skip_consent": false, "subject_type": "", "token_endpoint_auth_method": "client_secret_post", "tos_uri": "" }
JSON
hydra/cmd/.snapshots/TestGetClient-case=gets_multiple_clients.json
[ { "allowed_cors_origins": [], "audience": [], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "contacts": [], "grant_types": [], "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "redirect_uris": [], "response_types": [], "scope": "", "skip_consent": false, "subject_type": "", "token_endpoint_auth_method": "client_secret_post", "tos_uri": "" }, { "allowed_cors_origins": [], "audience": [], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "contacts": [], "grant_types": [], "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "redirect_uris": [], "response_types": [], "scope": "", "skip_consent": false, "subject_type": "", "token_endpoint_auth_method": "client_secret_post", "tos_uri": "" } ]
JSON
hydra/cmd/.snapshots/TestImportClient-case=imports_clients_from_single_file.json
[ { "allowed_cors_origins": [], "audience": [], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "scope": "foo", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }, { "allowed_cors_origins": [], "audience": [], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "scope": "bar", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" } ]
JSON
hydra/cmd/.snapshots/TestImportClient-case=performs_appropriate_error_reporting.json
[ { "allowed_cors_origins": [], "audience": [], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "scope": "foo", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }, { "allowed_cors_origins": [], "audience": [], "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "scope": "bar", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" } ]
JSON
hydra/cmd/.snapshots/TestImportJWKS-case=imports_JWK_key_from_STDIN.json
{ "keys": [ { "alg": "RS256", "d": "GtgNgOZeibUHNRI8TWz-KG-3VCGoDyeafmL9pR5mRz1eh9bsZSqrjOXA_EoS0pEvQgdjsXDWzSGGEJcsDS4TsXc6IyDuVHVw6bk0jqRnzePILHGtHHUNRI7afFCi1-E-wMxtoOLJLhbES2zRynZJgmF1h3-NMf24N-a34MbBA3smLGKjUOPe_AHuSsNj6Z2t7hIVjsZuT1XGQOAuAIsyirnab7Bi58_wJOCkoWkxvb_ImtsuG4nFhmsnep3-hij_3WTq_vGUEoQ6TAPa94aT0OqLxg83FpGS1MSOdlvrJuF7Nq33f5VXGrg56bfAzCi7VJ9etJQq2Az-nYe9_D_voQ", "dp": "ezNSf4RjC3FKY3LODFwoFV124sNnOr9a_c5rSuKHRHuNj2dHDcKWP1wGcjWQAHu0NLLcS-OCuDVhJsQvNMe5V2SqM8_eljqTZzteqhgtyDBwE_yQ-Tq_tOFk09eFHu1BKfKnCEA06WyfQ8SpP3oJUox_kiB3ilCzl8O30ru6eCE", "dq": "GfJVyEhQxKcG0JqCmfgMrAOOJ_ecRj4Y2Zv8PaACs2LLlRpiTmrASZXnCzkaTNuJJTTsBQOHmJ4eB62Tl0eFRrJlw5ItZ4FEUItWe9SLSdlgRk1vWpkZ0MbzMZx01fP2ox3vpDL9YAD-dlP5mfUCLB4Ci8XFDxr961E9_ZkNtTU", "e": "AQAB", "kty": "RSA", "n": "slWybuiNYR7uOgKuvaBwqVk8saEutKhOAaW-3hWF65gJei-ZV8QFfYDxs9ZaRZlWAUMtncQPnw7ZQlXO9ogN5cMcN50C6qMOOZzghK7danalhF5lUETC4Hk3Eisbi_PR3IfVyXaRmqL6X66MKj_JAKyD9NFIDVy52K8A198Jojnrw2-XXQW72U68fZtvlyl_BTBWQ9Re5JSTpEcVmpCR8FrFc0RPMBm-G5dRs08vvhZNiTT2JACO5V-J5ZrgP3s5hnGFcQFZgDnXLInDUdoi1MuCjaAU0ta8_08pHMijNix5kFofdPEB954MiZ9k4kQ5_utt02I9x2ssHqw71ojjvw", "p": "2fNL9tC8u9M0wjA-kvvtDG96qO6O66Hksssy6RWInD-Iqk3MtHQtLeoCjvX-zERqwOb6SI6empk5pZ9E3_9vJ0dBqkxx3nqn4M_nRWnExGgngJsL959tf50cdxva8y1RjNhT4kCwTrupX_TP8lAG8SfG1Alo2VFR8iWd8hDQcTE", "q": "0XfjEgqAsVh4U0s3lFxKjOepEyp0G1Imty5J16SvcOEAD1Mrmz94aSSp0bYhXNVdbf7nRk77htWC7SE29fGjOzZRS76wxj_SJHF-rktHB2Zt23k1jBeZ4uLMPMnGLY_BJ0995DTGo0yU0rrPbyXosx-ukfQLAHFuggX4RNeM5-8", "qi": "HpCgP7B_4GTBe49H0AQueQHBn4RIkgqMy9xiMeR-U-U0vaY0TlfLhnX-5PkNfkPXohXlfL7pxwZNYa6FZhCAubzvhKCdUASivkoGaIEk6g1VTVYS_eDVQ4CAslfl-elXtLq_l1kQ8C14jlHrQzSXx4PQvjDEnAmaHSJNz4mP9Fg", "use": "sig" } ] }
JSON
hydra/cmd/.snapshots/TestRevokeToken-case=revokes_valid_token_but_without_client_credentials.json
"Usage:\n token the-token [flags]\n\nExamples:\n{{ .CommandPath }} --client-id a0184d6c-b313-4e70-a0b9-905b581e9218 --client-secret Hh1BjioNNm ciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNT\n\nFlags:\n --client-id string Use the provided OAuth 2.0 Client ID, defaults to environment variable OAUTH2_CLIENT_ID\n --client-secret string Use the provided OAuth 2.0 Client Secret, defaults to environment variable OAUTH2_CLIENT_SECRET\n -e, --endpoint string The API URL this command should target. Alternatively set using the ORY_SDK_URL environmental variable.\n --format string Set the output format. One of table, json, yaml, json-pretty, jsonpath and jsonpointer. (default \"default\")\n -h, --help help for token\n -H, --http-header : A list of additional HTTP headers to set. HTTP headers is separated by a : , for example: `-H 'Authorization: bearer some-token'`.\n -q, --quiet Be quiet with output printing.\n --skip-tls-verify Do not verify TLS certificates. Useful when dealing with self-signed certificates. Do not use in production!\n\n\nPlease provide a Client ID and Client Secret using flags --client-id and --client-secret, or environment variables OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET\n"
JSON
hydra/cmd/.snapshots/TestUpdateClient-case=creates_successfully.json
{ "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "grant_types": [ "implicit" ], "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "request_object_signing_alg": "RS256", "response_types": [ "code" ], "scope": "offline_access offline openid", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }
JSON
hydra/cmd/.snapshots/TestUpdateClient-case=supports_encryption.json
{ "client_name": "", "client_secret_expires_at": 0, "client_uri": "", "grant_types": [ "implicit" ], "jwks": {}, "logo_uri": "", "metadata": {}, "owner": "", "policy_uri": "", "request_object_signing_alg": "RS256", "response_types": [ "code" ], "scope": "offline_access offline openid", "skip_consent": false, "subject_type": "public", "token_endpoint_auth_method": "client_secret_basic", "tos_uri": "", "userinfo_signed_response_alg": "none" }
Go
hydra/cmd/cli/error.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( "bytes" "encoding/json" ) func FormatSwaggerError(err error) string { if err == nil { return "" } var b bytes.Buffer if err := json.NewEncoder(&b).Encode(err); err != nil { panic(err) } var e struct { Payload json.RawMessage } if err := json.NewDecoder(&b).Decode(&e); err != nil { panic(err) } if len(e.Payload) == 0 { return err.Error() } dec := json.NewEncoder(&b) dec.SetIndent("", " ") if err := dec.Encode(e.Payload); err != nil { panic(err) } return b.String() }
Go
hydra/cmd/cli/handler.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( "github.com/ory/hydra/v2/driver" "github.com/ory/x/configx" "github.com/ory/x/servicelocatorx" ) type Handler struct { Migration *MigrateHandler Janitor *JanitorHandler } func NewHandler(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *Handler { return &Handler{ Migration: newMigrateHandler(slOpts, dOpts, cOpts), Janitor: NewJanitorHandler(slOpts, dOpts, cOpts), } }
Go
hydra/cmd/cli/handler_helper.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( "net/http" "github.com/sawadashota/encrypta" "github.com/spf13/cobra" "github.com/ory/x/flagx" ) const ( FlagEncryptionPGPKey = "pgp-key" FlagEncryptionPGPKeyURL = "pgp-key-url" FlagEncryptionKeybase = "keybase" ) // NewEncryptionKey for client secret func NewEncryptionKey(cmd *cobra.Command, client *http.Client) (ek encrypta.EncryptionKey, encryptSecret bool, err error) { if client == nil { client = http.DefaultClient } pgpKey := flagx.MustGetString(cmd, FlagEncryptionPGPKey) pgpKeyURL := flagx.MustGetString(cmd, FlagEncryptionPGPKeyURL) keybaseUsername := flagx.MustGetString(cmd, FlagEncryptionKeybase) if pgpKey != "" { ek, err = encrypta.NewPublicKeyFromBase64Encoded(pgpKey) encryptSecret = true return } if pgpKeyURL != "" { ek, err = encrypta.NewPublicKeyFromURL(pgpKeyURL, encrypta.HTTPClientOption(client)) encryptSecret = true return } if keybaseUsername != "" { ek, err = encrypta.NewPublicKeyFromKeybase(keybaseUsername, encrypta.HTTPClientOption(client)) encryptSecret = true return } return nil, false, nil }
Go
hydra/cmd/cli/handler_janitor.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( "context" "fmt" "io" "time" "github.com/ory/x/servicelocatorx" "github.com/ory/hydra/v2/persistence" "github.com/pkg/errors" "github.com/ory/x/flagx" "github.com/spf13/cobra" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/driver/config" "github.com/ory/x/configx" "github.com/ory/x/errorsx" ) const ( Limit = "limit" BatchSize = "batch-size" KeepIfYounger = "keep-if-younger" AccessLifespan = "access-lifespan" RefreshLifespan = "refresh-lifespan" ConsentRequestLifespan = "consent-request-lifespan" OnlyTokens = "tokens" OnlyRequests = "requests" OnlyGrants = "grants" ReadFromEnv = "read-from-env" Config = "config" ) type JanitorHandler struct { slOpts []servicelocatorx.Option dOpts []driver.OptionsModifier cOpts []configx.OptionModifier } func NewJanitorHandler(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *JanitorHandler { return &JanitorHandler{ slOpts: slOpts, dOpts: dOpts, cOpts: cOpts, } } func (*JanitorHandler) Args(cmd *cobra.Command, args []string) error { if len(args) == 0 && !flagx.MustGetBool(cmd, ReadFromEnv) && len(flagx.MustGetStringSlice(cmd, Config)) == 0 { fmt.Printf("%s\n", cmd.UsageString()) //lint:ignore ST1005 formatted error string used in CLI output return fmt.Errorf("%s\n%s\n%s\n", "A DSN is required as a positional argument when not passing any of the following flags:", "- Using the environment variable with flag -e, --read-from-env", "- Using the config file with flag -c, --config") } if !flagx.MustGetBool(cmd, OnlyTokens) && !flagx.MustGetBool(cmd, OnlyRequests) && !flagx.MustGetBool(cmd, OnlyGrants) { //lint:ignore ST1005 formatted error string used in CLI output return fmt.Errorf("%s\n%s\n", cmd.UsageString(), "Janitor requires at least one of --tokens, --requests or --grants to be set") } limit := flagx.MustGetInt(cmd, Limit) batchSize := flagx.MustGetInt(cmd, BatchSize) if limit <= 0 || batchSize <= 0 { //lint:ignore ST1005 formatted error string used in CLI output return fmt.Errorf("%s\n%s\n", cmd.UsageString(), "Values for --limit and --batch-size should both be greater than 0") } if batchSize > limit { //lint:ignore ST1005 formatted error string used in CLI output return fmt.Errorf("%s\n%s\n", cmd.UsageString(), "Value for --batch-size must not be greater than value for --limit") } return nil } func (j *JanitorHandler) RunE(cmd *cobra.Command, args []string) error { return purge(cmd, args, servicelocatorx.NewOptions(j.slOpts...), j.dOpts) } func purge(cmd *cobra.Command, args []string, sl *servicelocatorx.Options, dOpts []driver.OptionsModifier) error { ctx := cmd.Context() var d driver.Registry co := []configx.OptionModifier{ configx.WithFlags(cmd.Flags()), configx.SkipValidation(), } keys := map[string]string{ AccessLifespan: config.KeyAccessTokenLifespan, RefreshLifespan: config.KeyRefreshTokenLifespan, ConsentRequestLifespan: config.KeyConsentRequestMaxAge, } for k, v := range keys { if x := flagx.MustGetDuration(cmd, k); x > 0 { co = append(co, configx.WithValue(v, x)) } } notAfter := time.Now() if keepYounger := flagx.MustGetDuration(cmd, KeepIfYounger); keepYounger > 0 { notAfter = notAfter.Add(-keepYounger) } if !flagx.MustGetBool(cmd, ReadFromEnv) && len(flagx.MustGetStringSlice(cmd, Config)) == 0 { co = append(co, configx.WithValue(config.KeyDSN, args[0])) } do := append(dOpts, driver.DisableValidation(), driver.DisablePreloading(), driver.WithOptions(co...), ) d, err := driver.New(ctx, sl, do) if err != nil { return errors.Wrap(err, "Could not create driver") } if len(d.Config().DSN()) == 0 { //lint:ignore ST1005 formatted error string used in CLI output return fmt.Errorf("%s\n%s\n%s\n", cmd.UsageString(), "When using flag -e, environment variable DSN must be set.", "When using flag -c, the dsn property should be set.") } p := d.Persister() limit := flagx.MustGetInt(cmd, Limit) batchSize := flagx.MustGetInt(cmd, BatchSize) var routineFlags []string if flagx.MustGetBool(cmd, OnlyTokens) { routineFlags = append(routineFlags, OnlyTokens) } if flagx.MustGetBool(cmd, OnlyRequests) { routineFlags = append(routineFlags, OnlyRequests) } if flagx.MustGetBool(cmd, OnlyGrants) { routineFlags = append(routineFlags, OnlyGrants) } return cleanupRun(cmd.Context(), notAfter, limit, batchSize, addRoutine(cmd.OutOrStdout(), p, routineFlags...)...) } func addRoutine(out io.Writer, p persistence.Persister, names ...string) []cleanupRoutine { var routines []cleanupRoutine for _, n := range names { switch n { case OnlyTokens: routines = append(routines, cleanup(out, p.FlushInactiveAccessTokens, "access tokens")) routines = append(routines, cleanup(out, p.FlushInactiveRefreshTokens, "refresh tokens")) case OnlyRequests: routines = append(routines, cleanup(out, p.FlushInactiveLoginConsentRequests, "login-consent requests")) case OnlyGrants: routines = append(routines, cleanup(out, p.FlushInactiveGrants, "grants")) } } return routines } type cleanupRoutine func(ctx context.Context, notAfter time.Time, limit int, batchSize int) error func cleanup(out io.Writer, cr cleanupRoutine, routineName string) cleanupRoutine { return func(ctx context.Context, notAfter time.Time, limit int, batchSize int) error { if err := cr(ctx, notAfter, limit, batchSize); err != nil { return errors.Wrap(errorsx.WithStack(err), fmt.Sprintf("Could not cleanup inactive %s", routineName)) } fmt.Fprintf(out, "Successfully completed Janitor run on %s\n", routineName) return nil } } func cleanupRun(ctx context.Context, notAfter time.Time, limit int, batchSize int, routines ...cleanupRoutine) error { if len(routines) == 0 { return errors.New("clean up run received 0 routines") } for _, r := range routines { if err := r(ctx, notAfter, limit, batchSize); err != nil { return err } } return nil }
Go
hydra/cmd/cli/handler_janitor_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli_test import ( "context" "fmt" "testing" "time" "github.com/ory/hydra/v2/cmd" "github.com/spf13/cobra" "github.com/stretchr/testify/require" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/hydra/v2/internal/testhelpers" "github.com/ory/x/cmdx" ) func newJanitorCmd() *cobra.Command { return cmd.NewRootCmd(nil, nil, nil) } func TestJanitorHandler_PurgeTokenNotAfter(t *testing.T) { ctx := context.Background() testCycles := testhelpers.NewConsentJanitorTestHelper("").GetNotAfterTestCycles() require.True(t, len(testCycles) > 0) for k, v := range testCycles { t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) { jt := testhelpers.NewConsentJanitorTestHelper(t.Name()) reg, err := jt.GetRegistry(ctx, k) require.NoError(t, err) // setup test t.Run("step=setup-access", jt.AccessTokenNotAfterSetup(ctx, reg.ClientManager(), reg.OAuth2Storage())) t.Run("step=setup-refresh", jt.RefreshTokenNotAfterSetup(ctx, reg.ClientManager(), reg.OAuth2Storage())) // run the cleanup routine t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s=%s", cli.KeepIfYounger, v.String()), fmt.Sprintf("--%s=%s", cli.AccessLifespan, jt.GetAccessTokenLifespan(ctx).String()), fmt.Sprintf("--%s=%s", cli.RefreshLifespan, jt.GetRefreshTokenLifespan(ctx).String()), fmt.Sprintf("--%s", cli.OnlyTokens), jt.GetDSN(), ) }) // validate test notAfter := time.Now().Round(time.Second).Add(-v) t.Run("step=validate-access", jt.AccessTokenNotAfterValidate(ctx, notAfter, reg.OAuth2Storage())) t.Run("step=validate-refresh", jt.RefreshTokenNotAfterValidate(ctx, notAfter, reg.OAuth2Storage())) }) } } func TestJanitorHandler_PurgeLoginConsentNotAfter(t *testing.T) { ctx := context.Background() testCycles := testhelpers.NewConsentJanitorTestHelper("").GetNotAfterTestCycles() for k, v := range testCycles { jt := testhelpers.NewConsentJanitorTestHelper(k) reg, err := jt.GetRegistry(ctx, k) require.NoError(t, err) t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) { // Setup the test t.Run("step=setup", jt.LoginConsentNotAfterSetup(ctx, reg.ConsentManager(), reg.ClientManager())) // Run the cleanup routine t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s=%s", cli.KeepIfYounger, v.String()), fmt.Sprintf("--%s=%s", cli.ConsentRequestLifespan, jt.GetConsentRequestLifespan(ctx).String()), fmt.Sprintf("--%s", cli.OnlyRequests), jt.GetDSN(), ) }) notAfter := time.Now().Round(time.Second).Add(-v) consentLifespan := time.Now().Round(time.Second).Add(-jt.GetConsentRequestLifespan(ctx)) t.Run("step=validate", jt.LoginConsentNotAfterValidate(ctx, notAfter, consentLifespan, reg)) }) } } func TestJanitorHandler_PurgeLoginConsent(t *testing.T) { /* Login and Consent also needs to be purged on two conditions besides the KeyConsentRequestMaxAge and notAfter time - when a login/consent request was never completed (timed out) - when a login/consent request was rejected */ t.Run("case=login-consent-timeout", func(t *testing.T) { t.Run("case=login-timeout", func(t *testing.T) { ctx := context.Background() jt := testhelpers.NewConsentJanitorTestHelper(t.Name()) reg, err := jt.GetRegistry(ctx, t.Name()) require.NoError(t, err) // setup t.Run("step=setup", jt.LoginTimeoutSetup(ctx, reg)) // cleanup t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), jt.GetDSN(), ) }) t.Run("step=validate", jt.LoginTimeoutValidate(ctx, reg.ConsentManager())) }) t.Run("case=consent-timeout", func(t *testing.T) { ctx := context.Background() jt := testhelpers.NewConsentJanitorTestHelper(t.Name()) reg, err := jt.GetRegistry(ctx, t.Name()) require.NoError(t, err) // setup t.Run("step=setup", jt.ConsentTimeoutSetup(ctx, reg)) // run cleanup t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), jt.GetDSN(), ) }) // validate t.Run("step=validate", jt.ConsentTimeoutValidate(ctx, reg.ConsentManager())) }) }) t.Run("case=login-consent-rejection", func(t *testing.T) { ctx := context.Background() t.Run("case=login-rejection", func(t *testing.T) { jt := testhelpers.NewConsentJanitorTestHelper(t.Name()) reg, err := jt.GetRegistry(ctx, t.Name()) require.NoError(t, err) // setup t.Run("step=setup", jt.LoginRejectionSetup(ctx, reg)) // cleanup t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), jt.GetDSN(), ) }) // validate t.Run("step=validate", jt.LoginRejectionValidate(ctx, reg.ConsentManager())) }) t.Run("case=consent-rejection", func(t *testing.T) { jt := testhelpers.NewConsentJanitorTestHelper(t.Name()) reg, err := jt.GetRegistry(ctx, t.Name()) require.NoError(t, err) // setup t.Run("step=setup", jt.ConsentRejectionSetup(ctx, reg)) // cleanup t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), jt.GetDSN(), ) }) // validate t.Run("step=validate", jt.ConsentRejectionValidate(ctx, reg.ConsentManager())) }) }) } func TestJanitorHandler_Arguments(t *testing.T) { cmdx.ExecNoErr(t, cmd.NewRootCmd(nil, nil, nil), "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), "memory", ) cmdx.ExecNoErr(t, cmd.NewRootCmd(nil, nil, nil), "janitor", fmt.Sprintf("--%s", cli.OnlyTokens), "memory", ) cmdx.ExecNoErr(t, cmd.NewRootCmd(nil, nil, nil), "janitor", fmt.Sprintf("--%s", cli.OnlyGrants), "memory", ) _, _, err := cmdx.ExecCtx(context.Background(), cmd.NewRootCmd(nil, nil, nil), nil, "janitor", "memory") require.Error(t, err) require.Contains(t, err.Error(), "Janitor requires at least one of --tokens, --requests or --grants to be set") cmdx.ExecNoErr(t, cmd.NewRootCmd(nil, nil, nil), "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), fmt.Sprintf("--%s=%s", cli.Limit, "1000"), fmt.Sprintf("--%s=%s", cli.BatchSize, "100"), "memory", ) _, _, err = cmdx.ExecCtx(context.Background(), cmd.NewRootCmd(nil, nil, nil), nil, "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), fmt.Sprintf("--%s=%s", cli.Limit, "0"), "memory") require.Error(t, err) require.Contains(t, err.Error(), "Values for --limit and --batch-size should both be greater than 0") _, _, err = cmdx.ExecCtx(context.Background(), cmd.NewRootCmd(nil, nil, nil), nil, "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), fmt.Sprintf("--%s=%s", cli.Limit, "-100"), "memory") require.Error(t, err) require.Contains(t, err.Error(), "Values for --limit and --batch-size should both be greater than 0") _, _, err = cmdx.ExecCtx(context.Background(), cmd.NewRootCmd(nil, nil, nil), nil, "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), fmt.Sprintf("--%s=%s", cli.BatchSize, "0"), "memory") require.Error(t, err) require.Contains(t, err.Error(), "Values for --limit and --batch-size should both be greater than 0") _, _, err = cmdx.ExecCtx(context.Background(), cmd.NewRootCmd(nil, nil, nil), nil, "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), fmt.Sprintf("--%s=%s", cli.BatchSize, "-100"), "memory") require.Error(t, err) require.Contains(t, err.Error(), "Values for --limit and --batch-size should both be greater than 0") _, _, err = cmdx.ExecCtx(context.Background(), cmd.NewRootCmd(nil, nil, nil), nil, "janitor", fmt.Sprintf("--%s", cli.OnlyRequests), fmt.Sprintf("--%s=%s", cli.Limit, "100"), fmt.Sprintf("--%s=%s", cli.BatchSize, "1000"), "memory") require.Error(t, err) require.Contains(t, err.Error(), "Value for --batch-size must not be greater than value for --limit") } func TestJanitorHandler_PurgeGrantNotAfter(t *testing.T) { ctx := context.Background() testCycles := testhelpers.NewConsentJanitorTestHelper("").GetNotAfterTestCycles() require.True(t, len(testCycles) > 0) for k, v := range testCycles { t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) { jt := testhelpers.NewConsentJanitorTestHelper(t.Name()) reg, err := jt.GetRegistry(ctx, k) require.NoError(t, err) // setup test t.Run("step=setup", jt.GrantNotAfterSetup(ctx, reg.GrantManager())) // run the cleanup routine t.Run("step=cleanup", func(t *testing.T) { cmdx.ExecNoErr(t, newJanitorCmd(), "janitor", fmt.Sprintf("--%s=%s", cli.KeepIfYounger, v.String()), fmt.Sprintf("--%s", cli.OnlyGrants), jt.GetDSN(), ) }) // validate test notAfter := time.Now().Round(time.Second).Add(-v) t.Run("step=validate-access", jt.GrantNotAfterValidate(ctx, notAfter, reg.GrantManager())) }) } }
Go
hydra/cmd/cli/handler_jwk.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( jose "github.com/go-jose/go-jose/v3" ) func ToSDKFriendlyJSONWebKey(key interface{}, kid, use string) jose.JSONWebKey { var alg string if jwk, ok := key.(*jose.JSONWebKey); ok { key = jwk.Key if jwk.KeyID != "" { kid = jwk.KeyID } if jwk.Use != "" { use = jwk.Use } if jwk.Algorithm != "" { alg = jwk.Algorithm } } return jose.JSONWebKey{ KeyID: kid, Use: use, Algorithm: alg, Key: key, } }
Go
hydra/cmd/cli/handler_jwk_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( "testing" "github.com/ory/x/josex" ) func Test_toSDKFriendlyJSONWebKey(t *testing.T) { publicJWK := []byte(`{ "kty": "RSA", "e": "AQAB", "use": "sig", "kid": "7a5ff76a-6766-11ea-bc55-0242ac130003", "alg": "RS256", "n": "l80jJJqcc1PpefIGVIjuPvA1D7NscnuF9aQqLa7I9rDUK4IaSOO3kL_EF13k-jTzcA5q4OZn5dR0kmqIMZT2gQ" }`) publicPEM := []byte(` -----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPf64dykufSkwnvUiBAwd5Si0K6t4m5i qJD8TmLJCmFjKaOUa6nszcFt/FkAuORfdlrD9mEZLPrPx74RSluyTBMCAwEAAQ== -----END PUBLIC KEY----- `) type args struct { key []byte kid string use string } tests := []struct { name string args args want string }{ { name: "JWK with algorithm", args: args{ key: publicJWK, kid: "public:7a5ff76a-6766-11ea-bc55-0242ac130003", use: "sig", }, want: "RS256", }, { name: "PEM key without algorithm", args: args{ key: publicPEM, kid: "public:7a5ff76a-6766-11ea-bc55-0242ac130003", use: "sig", }, want: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { key, _ := josex.LoadPublicKey(tt.args.key) if got := ToSDKFriendlyJSONWebKey(key, tt.args.kid, tt.args.use); got.Algorithm != tt.want { t.Errorf("toSDKFriendlyJSONWebKey() = %v, want %v", got.Algorithm, tt.want) } }) } }
Go
hydra/cmd/cli/handler_migrate.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cli import ( "bytes" "context" "fmt" "io" "io/fs" "os" "path/filepath" "regexp" "strings" "time" "github.com/ory/x/popx" "github.com/ory/x/servicelocatorx" "github.com/pkg/errors" "github.com/ory/x/configx" "github.com/ory/x/errorsx" "github.com/ory/x/cmdx" "github.com/spf13/cobra" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/persistence" "github.com/ory/x/flagx" ) type MigrateHandler struct { slOpts []servicelocatorx.Option dOpts []driver.OptionsModifier cOpts []configx.OptionModifier } func newMigrateHandler(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *MigrateHandler { return &MigrateHandler{ slOpts: slOpts, dOpts: dOpts, cOpts: cOpts, } } const ( genericDialectKey = "any" ) var fragmentHeader = []byte(strings.TrimLeft(` -- Migration generated by the command below; DO NOT EDIT. -- hydra:generate hydra migrate gen `, "\n")) var blankFragment = []byte(strings.TrimLeft(` -- This blank migration was generated to meet ory/x/popx validation criteria, see https://github.com/ory/x/pull/509; DO NOT EDIT. -- hydra:generate hydra migrate gen `, "\n")) var mrx = regexp.MustCompile(`^(\d{14})000000_([^.]+)(\.[a-z0-9]+)?\.(up|down)\.sql$`) type migration struct { Path string ID string Name string Dialect string Direction string } type migrationGroup struct { ID string Name string Children []*migration fallbackUpMigration *migration fallbackDownMigration *migration } func (m *migration) ReadSource(fs fs.FS) ([]byte, error) { f, err := fs.Open(m.Path) if err != nil { return nil, errors.WithStack(err) } defer f.Close() return io.ReadAll(f) } func (m migration) generateMigrationFragments(source []byte) ([][]byte, error) { chunks := bytes.Split(source, []byte("--split")) if len(chunks) < 1 { return nil, errors.New("no migration chunks found") } for i := range chunks { chunks[i] = append(fragmentHeader, chunks[i]...) } return chunks, nil } func (mg migrationGroup) fragmentName(m *migration, i int) string { if m.Dialect == genericDialectKey { return fmt.Sprintf("%s%06d_%s.%s.sql", mg.ID, i, mg.Name, m.Direction) } else { return fmt.Sprintf("%s%06d_%s.%s.%s.sql", mg.ID, i, mg.Name, m.Dialect, m.Direction) } } // GenerateSQL splits the migration sources into chunks and writes them to the // target directory. func (mg migrationGroup) generateSQL(sourceFS fs.FS, target string) error { ms := mg.Children if mg.fallbackDownMigration != nil { ms = append(ms, mg.fallbackDownMigration) } if mg.fallbackUpMigration != nil { ms = append(ms, mg.fallbackUpMigration) } dialectFragmentCounts := map[string]int{} maxFragmentCount := -1 for _, m := range ms { source, err := m.ReadSource(sourceFS) if err != nil { return errors.WithStack(err) } fragments, err := m.generateMigrationFragments(source) dialectFragmentCounts[m.Dialect] = len(fragments) if maxFragmentCount < len(fragments) { maxFragmentCount = len(fragments) } if err != nil { return errors.Errorf("failed to process %s: %s", m.Path, err.Error()) } for i, fragment := range fragments { dst := filepath.Join(target, mg.fragmentName(m, i)) if err = os.WriteFile(dst, fragment, 0600); err != nil { return errors.WithStack(errors.Errorf("failed to write file %s", dst)) } } } for _, m := range ms { for i := dialectFragmentCounts[m.Dialect]; i < maxFragmentCount; i += 1 { dst := filepath.Join(target, mg.fragmentName(m, i)) if err := os.WriteFile(dst, blankFragment, 0600); err != nil { return errors.WithStack(errors.Errorf("failed to write file %s", dst)) } } } return nil } func parseMigration(filename string) (*migration, error) { matches := mrx.FindAllStringSubmatch(filename, -1) if matches == nil { return nil, errors.Errorf("failed to parse migration filename %s; %s does not match pattern ", filename, mrx.String()) } if len(matches) != 1 && len(matches[0]) != 5 { return nil, errors.Errorf("invalid migration %s; expected %s", filename, mrx.String()) } dialect := matches[0][3] if dialect == "" { dialect = genericDialectKey } else { dialect = dialect[1:] } return &migration{ Path: filename, ID: matches[0][1], Name: matches[0][2], Dialect: dialect, Direction: matches[0][4], }, nil } func readMigrations(migrationSourceFS fs.FS, expectedDialects []string) (map[string]*migrationGroup, error) { mgs := make(map[string]*migrationGroup) err := fs.WalkDir(migrationSourceFS, ".", func(p string, d fs.DirEntry, err2 error) error { if err2 != nil { fmt.Println("Warning: unexpected error " + err2.Error()) return nil } if d.IsDir() { return nil } if p != filepath.Base(p) { fmt.Println("Warning: ignoring nested file " + p) return nil } m, err := parseMigration(p) if err != nil { return err } if _, ok := mgs[m.ID]; !ok { mgs[m.ID] = &migrationGroup{ ID: m.ID, Name: m.Name, Children: nil, } } if m.Dialect == genericDialectKey && m.Direction == "up" { mgs[m.ID].fallbackUpMigration = m } else if m.Dialect == genericDialectKey && m.Direction == "down" { mgs[m.ID].fallbackDownMigration = m } else { mgs[m.ID].Children = append(mgs[m.ID].Children, m) } return nil }) if err != nil { return nil, err } if len(expectedDialects) == 0 { return mgs, nil } eds := make(map[string]struct{}) for i := range expectedDialects { eds[expectedDialects[i]] = struct{}{} } for _, mg := range mgs { expect := make(map[string]struct{}) for _, m := range mg.Children { if _, ok := eds[m.Dialect]; !ok { return nil, errors.Errorf("unexpected dialect %s in filename %s", m.Dialect, m.Path) } expect[m.Dialect+"."+m.Direction] = struct{}{} } for _, d := range expectedDialects { if _, ok := expect[d+".up"]; !ok && mg.fallbackUpMigration == nil { return nil, errors.Errorf("dialect %s not found for up migration %s; use --dialects=\"\" to disable dialect validation", d, mg.ID) } if _, ok := expect[d+".down"]; !ok && mg.fallbackDownMigration == nil { return nil, errors.Errorf("dialect %s not found for down migration %s; use --dialects=\"\" to disable dialect validation", d, mg.ID) } } } return mgs, nil } func (h *MigrateHandler) MigrateGen(cmd *cobra.Command, args []string) { cmdx.ExactArgs(cmd, args, 2) expectedDialects := flagx.MustGetStringSlice(cmd, "dialects") sourceDir := args[0] targetDir := args[1] sourceFS := os.DirFS(sourceDir) mgs, err := readMigrations(sourceFS, expectedDialects) if err != nil { fmt.Println(err.Error()) os.Exit(1) } for _, mg := range mgs { err = mg.generateSQL(sourceFS, targetDir) if err != nil { fmt.Println(err.Error()) os.Exit(1) } } os.Exit(0) } func (h *MigrateHandler) makePersister(cmd *cobra.Command, args []string) (p persistence.Persister, err error) { var d driver.Registry if flagx.MustGetBool(cmd, "read-from-env") { d, err = driver.New( cmd.Context(), servicelocatorx.NewOptions(), append([]driver.OptionsModifier{ driver.WithOptions( configx.SkipValidation(), configx.WithFlags(cmd.Flags())), driver.DisableValidation(), driver.DisablePreloading(), driver.SkipNetworkInit(), }, h.dOpts...)) if err != nil { return nil, err } if len(d.Config().DSN()) == 0 { _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "When using flag -e, environment variable DSN must be set.") return nil, cmdx.FailSilently(cmd) } } else { if len(args) != 1 { _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "Please provide the database URL.") return nil, cmdx.FailSilently(cmd) } d, err = driver.New( cmd.Context(), servicelocatorx.NewOptions(), append([]driver.OptionsModifier{ driver.WithOptions( configx.WithFlags(cmd.Flags()), configx.SkipValidation(), configx.WithValue(config.KeyDSN, args[0]), ), driver.DisableValidation(), driver.DisablePreloading(), driver.SkipNetworkInit(), }, h.dOpts...)) if err != nil { return nil, err } } return d.Persister(), nil } func (h *MigrateHandler) MigrateSQL(cmd *cobra.Command, args []string) (err error) { p, err := h.makePersister(cmd, args) if err != nil { return err } conn := p.Connection(context.Background()) if conn == nil { _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "Migrations can only be executed against a SQL-compatible driver but DSN is not a SQL source.") return cmdx.FailSilently(cmd) } if err := conn.Open(); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not open the database connection:\n%+v\n", err) return cmdx.FailSilently(cmd) } // convert migration tables if err := p.PrepareMigration(context.Background()); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not convert the migration table:\n%+v\n", err) return cmdx.FailSilently(cmd) } // print migration status _, _ = fmt.Fprintln(cmd.OutOrStdout(), "The following migration is planned:") status, err := p.MigrationStatus(context.Background()) if err != nil { fmt.Fprintf(cmd.ErrOrStderr(), "Could not get the migration status:\n%+v\n", errorsx.WithStack(err)) return cmdx.FailSilently(cmd) } _ = status.Write(os.Stdout) if !flagx.MustGetBool(cmd, "yes") { _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "To skip the next question use flag --yes (at your own risk).") if !cmdx.AskForConfirmation("Do you wish to execute this migration plan?", nil, nil) { _, _ = fmt.Fprintln(cmd.OutOrStdout(), "Migration aborted.") return nil } } // apply migrations if err := p.MigrateUp(context.Background()); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not apply migrations:\n%+v\n", errorsx.WithStack(err)) return cmdx.FailSilently(cmd) } _, _ = fmt.Fprintln(cmd.OutOrStdout(), "Successfully applied migrations!") return nil } func (h *MigrateHandler) MigrateStatus(cmd *cobra.Command, args []string) error { p, err := h.makePersister(cmd, args) if err != nil { return err } conn := p.Connection(context.Background()) if conn == nil { _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "Migrations can only be checked against a SQL-compatible driver but DSN is not a SQL source.") return cmdx.FailSilently(cmd) } if err := conn.Open(); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not open the database connection:\n%+v\n", err) return cmdx.FailSilently(cmd) } block := flagx.MustGetBool(cmd, "block") ctx := cmd.Context() s, err := p.MigrationStatus(ctx) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not get migration status: %+v\n", err) return cmdx.FailSilently(cmd) } for block && s.HasPending() { _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Waiting for migrations to finish...\n") for _, m := range s { if m.State == popx.Pending { _, _ = fmt.Fprintf(cmd.OutOrStdout(), " - %s\n", m.Name) } } time.Sleep(time.Second) s, err = p.MigrationStatus(ctx) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not get migration status: %+v\n", err) return cmdx.FailSilently(cmd) } } cmdx.PrintTable(cmd, s) return nil }
Go
hydra/cmd/cliclient/client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cliclient import ( "net/url" "github.com/pkg/errors" "github.com/ory/x/cmdx" "github.com/spf13/cobra" hydra "github.com/ory/hydra-client-go/v2" ) type ContextKey int const ( ClientContextKey ContextKey = iota + 1 OAuth2URLOverrideContextKey ) func GetOAuth2URLOverride(cmd *cobra.Command, fallback *url.URL) *url.URL { if override, ok := cmd.Context().Value(OAuth2URLOverrideContextKey).(func(cmd *cobra.Command) *url.URL); ok { return override(cmd) } return fallback } func NewClient(cmd *cobra.Command) (*hydra.APIClient, *url.URL, error) { if f, ok := cmd.Context().Value(ClientContextKey).(func(cmd *cobra.Command) (*hydra.APIClient, *url.URL, error)); ok { return f(cmd) } hc, target, err := cmdx.NewClient(cmd) if err != nil { return nil, nil, errors.WithStack(err) } conf := hydra.NewConfiguration() conf.HTTPClient = hc conf.Servers = hydra.ServerConfigurations{{URL: target.String()}} return hydra.NewAPIClient(conf), target, nil }
Go
hydra/cmd/clidoc/main.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package main import ( "fmt" "os" "github.com/ory/x/clidoc" "github.com/ory/hydra/v2/cmd" ) func main() { if err := clidoc.Generate(cmd.NewRootCmd(nil, nil, nil), os.Args[1:]); err != nil { _, _ = fmt.Fprintf(os.Stderr, "%+v", err) os.Exit(1) } fmt.Println("All files have been generated and updated.") }
Go
hydra/cmd/server/banner.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package server func banner(version string) string { return `Thank you for using Ory Hydra ` + version + `! Take security seriously and subscribe to the Ory Security Newsletter. Stay on top of new patches and security insights. >> Subscribe now: http://eepurl.com/di390P <<` }
Go
hydra/cmd/server/handler.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package server import ( "context" "crypto/tls" "fmt" "net/http" "strings" "sync" "time" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "github.com/ory/x/otelx/semconv" "github.com/ory/x/servicelocatorx" "github.com/ory/x/httprouterx" "github.com/ory/analytics-go/v5" "github.com/ory/x/configx" "github.com/ory/x/reqlog" "github.com/julienschmidt/httprouter" "github.com/rs/cors" "github.com/spf13/cobra" "github.com/urfave/negroni" "go.uber.org/automaxprocs/maxprocs" "github.com/ory/graceful" "github.com/ory/x/healthx" "github.com/ory/x/metricsx" "github.com/ory/x/networkx" "github.com/ory/x/otelx" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/jwk" "github.com/ory/hydra/v2/oauth2" "github.com/ory/hydra/v2/x" prometheus "github.com/ory/x/prometheusx" ) var _ = &consent.Handler{} func EnhanceMiddleware(ctx context.Context, sl *servicelocatorx.Options, d driver.Registry, n *negroni.Negroni, address string, router *httprouter.Router, iface config.ServeInterface) http.Handler { if !networkx.AddressIsUnixSocket(address) { n.UseFunc(x.RejectInsecureRequests(d, d.Config().TLS(ctx, iface))) } for _, mw := range sl.HTTPMiddlewares() { n.UseFunc(mw) } n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { cfg, enabled := d.Config().CORS(r.Context(), iface) if !enabled { next(w, r) return } cors.New(cfg).ServeHTTP(w, r, next) }) n.UseHandler(router) return n } func ensureNoMemoryDSN(r driver.Registry) { if r.Config().DSN() == "memory" { r.Logger().Fatalf(`When using "hydra serve admin" or "hydra serve public" the DSN can not be set to "memory".`) } } func RunServeAdmin(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() sl := servicelocatorx.NewOptions(slOpts...) d, err := driver.New(cmd.Context(), sl, append(dOpts, driver.WithOptions(append(cOpts, configx.WithFlags(cmd.Flags()))...))) if err != nil { return err } ensureNoMemoryDSN(d) admin, _, adminmw, _ := setup(ctx, d, cmd) d.PrometheusManager().RegisterRouter(admin.Router) var wg sync.WaitGroup wg.Add(1) go serve( ctx, d, cmd, &wg, config.AdminInterface, EnhanceMiddleware(ctx, sl, d, adminmw, d.Config().ListenOn(config.AdminInterface), admin.Router, config.AdminInterface), d.Config().ListenOn(config.AdminInterface), d.Config().SocketPermission(config.AdminInterface), ) wg.Wait() return nil } } func RunServePublic(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() sl := servicelocatorx.NewOptions(slOpts...) d, err := driver.New(cmd.Context(), sl, append(dOpts, driver.WithOptions(append(cOpts, configx.WithFlags(cmd.Flags()))...))) if err != nil { return err } ensureNoMemoryDSN(d) _, public, _, publicmw := setup(ctx, d, cmd) d.PrometheusManager().RegisterRouter(public.Router) var wg sync.WaitGroup wg.Add(1) go serve( ctx, d, cmd, &wg, config.PublicInterface, EnhanceMiddleware(ctx, sl, d, publicmw, d.Config().ListenOn(config.PublicInterface), public.Router, config.PublicInterface), d.Config().ListenOn(config.PublicInterface), d.Config().SocketPermission(config.PublicInterface), ) wg.Wait() return nil } } func RunServeAll(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() sl := servicelocatorx.NewOptions(slOpts...) d, err := driver.New(cmd.Context(), sl, append(dOpts, driver.WithOptions(append(cOpts, configx.WithFlags(cmd.Flags()))...))) if err != nil { return err } admin, public, adminmw, publicmw := setup(ctx, d, cmd) d.PrometheusManager().RegisterRouter(admin.Router) d.PrometheusManager().RegisterRouter(public.Router) var wg sync.WaitGroup wg.Add(2) go serve( ctx, d, cmd, &wg, config.PublicInterface, EnhanceMiddleware(ctx, sl, d, publicmw, d.Config().ListenOn(config.PublicInterface), public.Router, config.PublicInterface), d.Config().ListenOn(config.PublicInterface), d.Config().SocketPermission(config.PublicInterface), ) go serve( ctx, d, cmd, &wg, config.AdminInterface, EnhanceMiddleware(ctx, sl, d, adminmw, d.Config().ListenOn(config.AdminInterface), admin.Router, config.AdminInterface), d.Config().ListenOn(config.AdminInterface), d.Config().SocketPermission(config.AdminInterface), ) wg.Wait() return nil } } func setup(ctx context.Context, d driver.Registry, cmd *cobra.Command) (admin *httprouterx.RouterAdmin, public *httprouterx.RouterPublic, adminmw, publicmw *negroni.Negroni) { fmt.Println(banner(config.Version)) if d.Config().CGroupsV1AutoMaxProcsEnabled() { _, err := maxprocs.Set(maxprocs.Logger(d.Logger().Infof)) if err != nil { d.Logger().WithError(err).Fatal("Couldn't set GOMAXPROCS") } } adminmw = negroni.New() publicmw = negroni.New() admin = x.NewRouterAdmin(d.Config().AdminURL) public = x.NewRouterPublic() adminLogger := reqlog. NewMiddlewareFromLogger(d.Logger(), fmt.Sprintf("hydra/admin: %s", d.Config().IssuerURL(ctx).String())) if d.Config().DisableHealthAccessLog(config.AdminInterface) { adminLogger = adminLogger.ExcludePaths(healthx.AliveCheckPath, healthx.ReadyCheckPath, "/admin"+prometheus.MetricsPrometheusPath) } adminmw.UseFunc(semconv.Middleware) adminmw.Use(adminLogger) adminmw.Use(d.PrometheusManager()) publicLogger := reqlog.NewMiddlewareFromLogger( d.Logger(), fmt.Sprintf("hydra/public: %s", d.Config().IssuerURL(ctx).String()), ) if d.Config().DisableHealthAccessLog(config.PublicInterface) { publicLogger.ExcludePaths(healthx.AliveCheckPath, healthx.ReadyCheckPath) } publicmw.UseFunc(semconv.Middleware) publicmw.Use(publicLogger) publicmw.Use(d.PrometheusManager()) metrics := metricsx.New( cmd, d.Logger(), d.Config().Source(ctx), &metricsx.Options{ Service: "hydra", DeploymentId: metricsx.Hash(d.Persister().NetworkID(ctx).String()), IsDevelopment: d.Config().DSN() == "memory" || d.Config().IssuerURL(ctx).String() == "" || strings.Contains(d.Config().IssuerURL(ctx).String(), "localhost"), WriteKey: "h8dRH3kVCWKkIFWydBmWsyYHR4M0u0vr", WhitelistedPaths: []string{ "/admin" + jwk.KeyHandlerPath, jwk.WellKnownKeysPath, "/admin" + client.ClientsHandlerPath, client.DynClientsHandlerPath, oauth2.DefaultConsentPath, oauth2.DefaultLoginPath, oauth2.DefaultPostLogoutPath, oauth2.DefaultLogoutPath, oauth2.DefaultErrorPath, oauth2.TokenPath, oauth2.AuthPath, oauth2.LogoutPath, oauth2.UserinfoPath, oauth2.WellKnownPath, oauth2.JWKPath, "/admin" + oauth2.IntrospectPath, "/admin" + oauth2.DeleteTokensPath, oauth2.RevocationPath, "/admin" + consent.ConsentPath, "/admin" + consent.ConsentPath + "/accept", "/admin" + consent.ConsentPath + "/reject", "/admin" + consent.LoginPath, "/admin" + consent.LoginPath + "/accept", "/admin" + consent.LoginPath + "/reject", "/admin" + consent.LogoutPath, "/admin" + consent.LogoutPath + "/accept", "/admin" + consent.LogoutPath + "/reject", "/admin" + consent.SessionsPath + "/login", "/admin" + consent.SessionsPath + "/consent", healthx.AliveCheckPath, healthx.ReadyCheckPath, "/admin" + healthx.AliveCheckPath, "/admin" + healthx.ReadyCheckPath, healthx.VersionPath, "/admin" + healthx.VersionPath, prometheus.MetricsPrometheusPath, "/admin" + prometheus.MetricsPrometheusPath, "/", }, BuildVersion: config.Version, BuildTime: config.Date, BuildHash: config.Commit, Config: &analytics.Config{ Endpoint: "https://sqa.ory.sh", GzipCompressionLevel: 6, BatchMaxSize: 500 * 1000, BatchSize: 1000, Interval: time.Hour * 6, }, }, ) adminmw.Use(metrics) publicmw.Use(metrics) d.RegisterRoutes(ctx, admin, public) return } func serve( ctx context.Context, d driver.Registry, cmd *cobra.Command, wg *sync.WaitGroup, iface config.ServeInterface, handler http.Handler, address string, permission *configx.UnixPermission, ) { defer wg.Done() if tracer := d.Tracer(cmd.Context()); tracer.IsLoaded() { handler = otelx.TraceHandler( handler, otelhttp.WithTracerProvider(tracer.Provider()), otelhttp.WithFilter(func(r *http.Request) bool { return !strings.HasPrefix(r.URL.Path, "/admin/metrics/") }), ) } var tlsConfig *tls.Config stopReload := make(chan struct{}) if tc := d.Config().TLS(ctx, iface); tc.Enabled() { // #nosec G402 - This is a false positive because we use graceful.WithDefaults which sets the correct TLS settings. tlsConfig = &tls.Config{GetCertificate: GetOrCreateTLSCertificate(ctx, d, iface, stopReload)} } var srv = graceful.WithDefaults(&http.Server{ Handler: handler, TLSConfig: tlsConfig, ReadHeaderTimeout: time.Second * 5, }) if err := graceful.Graceful(func() error { d.Logger().Infof("Setting up http server on %s", address) listener, err := networkx.MakeListener(address, permission) if err != nil { return err } if networkx.AddressIsUnixSocket(address) { return srv.Serve(listener) } if tlsConfig != nil { return srv.ServeTLS(listener, "", "") } if iface == config.PublicInterface { d.Logger().Warnln("HTTPS is disabled. Please ensure that your proxy is configured to provide HTTPS, and that it redirects HTTP to HTTPS.") } return srv.Serve(listener) }, func(ctx context.Context) error { close(stopReload) return srv.Shutdown(ctx) }); err != nil { d.Logger().WithError(err).Fatal("Could not gracefully run server") } }
Go
hydra/cmd/server/helper_cert.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package server import ( "context" "crypto/sha1" // #nosec G505 - This is required for certificate chains alongside sha256 "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/pem" "sync" "github.com/gofrs/uuid" "github.com/go-jose/go-jose/v3" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/driver/config" "github.com/pkg/errors" "github.com/ory/x/tlsx" "github.com/ory/hydra/v2/jwk" ) const ( TlsKeyName = "hydra.https-tls" ) func AttachCertificate(priv *jose.JSONWebKey, cert *x509.Certificate) { priv.Certificates = []*x509.Certificate{cert} sig256 := sha256.Sum256(cert.Raw) // #nosec G401 - This is required for certificate chains alongside sha256 sig1 := sha1.Sum(cert.Raw) priv.CertificateThumbprintSHA256 = sig256[:] priv.CertificateThumbprintSHA1 = sig1[:] } var lock sync.Mutex // GetOrCreateTLSCertificate returns a function for use with // "net/tls".Config.GetCertificate. If the certificate and key are read from // disk, they will be automatically reloaded until stopReload is close()'d. func GetOrCreateTLSCertificate(ctx context.Context, d driver.Registry, iface config.ServeInterface, stopReload <-chan struct{}) func(*tls.ClientHelloInfo) (*tls.Certificate, error) { lock.Lock() defer lock.Unlock() // check if certificates are configured certFunc, err := d.Config().TLS(ctx, iface).GetCertificateFunc(stopReload, d.Logger()) if err == nil { return certFunc } else if !errors.Is(err, tlsx.ErrNoCertificatesConfigured) { d.Logger().WithError(err).Fatal("Unable to load HTTPS TLS Certificate") return nil // in case Fatal is hooked } // no certificates configured: self-sign a new cert priv, err := jwk.GetOrGenerateKeys(ctx, d, d.SoftwareKeyManager(), TlsKeyName, uuid.Must(uuid.NewV4()).String(), "RS256") if err != nil { d.Logger().WithError(err).Fatal("Unable to fetch or generate HTTPS TLS key pair") return nil // in case Fatal is hooked } if len(priv.Certificates) == 0 { cert, err := tlsx.CreateSelfSignedCertificate(priv.Key) if err != nil { d.Logger().WithError(err).Fatal(`Could not generate a self signed TLS certificate`) return nil // in case Fatal is hooked } AttachCertificate(priv, cert) if err := d.SoftwareKeyManager().DeleteKey(ctx, TlsKeyName, priv.KeyID); err != nil { d.Logger().WithError(err).Fatal(`Could not update (delete) the self signed TLS certificate`) return nil // in case Fatal is hooked } if err := d.SoftwareKeyManager().AddKey(ctx, TlsKeyName, priv); err != nil { d.Logger().WithError(err).Fatalf(`Could not update (add) the self signed TLS certificate: %s %x %d`, cert.SignatureAlgorithm, cert.Signature, len(cert.Signature)) return nil // in case Fatalf is hooked } } block, err := jwk.PEMBlockForKey(priv.Key) if err != nil { d.Logger().WithError(err).Fatal("Could not encode key to PEM") return nil // in case Fatal is hooked } if len(priv.Certificates) == 0 { d.Logger().Fatal("TLS certificate chain can not be empty") return nil // in case Fatal is hooked } pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: priv.Certificates[0].Raw}) pemKey := pem.EncodeToMemory(block) ct, err := tls.X509KeyPair(pemCert, pemKey) if err != nil { d.Logger().WithError(err).Fatal("Could not decode certificate") return nil // in case Fatal is hooked } return func(chi *tls.ClientHelloInfo) (*tls.Certificate, error) { return &ct, nil } }
Go
hydra/cmd/server/helper_cert_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package server_test import ( "bytes" "context" "crypto/x509" "encoding/base64" "encoding/json" "os" "testing" "time" "github.com/go-jose/go-jose/v3" "github.com/google/uuid" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/require" "github.com/ory/x/configx" "github.com/ory/x/logrusx" "github.com/ory/x/tlsx" "github.com/ory/hydra/v2/cmd/server" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/internal/testhelpers" "github.com/ory/hydra/v2/jwk" ) func TestGetOrCreateTLSCertificate(t *testing.T) { certPath, keyPath, cert, priv := testhelpers.GenerateTLSCertificateFilesForTests(t) logger := logrusx.New("", "") logger.Logger.ExitFunc = func(code int) { t.Fatalf("Logger called os.Exit(%v)", code) } hook := test.NewLocal(logger.Logger) cfg := config.MustNew( context.Background(), logger, configx.WithValues(map[string]interface{}{ "dsn": config.DSNMemory, "serve.tls.enabled": true, "serve.tls.cert.path": certPath, "serve.tls.key.path": keyPath, }), ) d, err := driver.NewRegistryWithoutInit(cfg, logger) require.NoError(t, err) getCert := server.GetOrCreateTLSCertificate(context.Background(), d, config.AdminInterface, nil) require.NotNil(t, getCert) tlsCert, err := getCert(nil) require.NoError(t, err) require.NotNil(t, tlsCert) if tlsCert.Leaf == nil { tlsCert.Leaf, err = x509.ParseCertificate(tlsCert.Certificate[0]) require.NoError(t, err) } require.True(t, tlsCert.Leaf.Equal(cert)) require.True(t, priv.Equal(tlsCert.PrivateKey)) // generate new cert+key newCertPath, newKeyPath, newCert, newPriv := testhelpers.GenerateTLSCertificateFilesForTests(t) require.False(t, cert.Equal(newCert)) require.False(t, priv.Equal(newPriv)) require.NotEqual(t, certPath, newCertPath) require.NotEqual(t, keyPath, newKeyPath) // move them into place require.NoError(t, os.Rename(newKeyPath, keyPath)) require.NoError(t, os.Rename(newCertPath, certPath)) // give it some time and check we're reloaded time.Sleep(150 * time.Millisecond) require.Nil(t, hook.LastEntry()) // request another certificate: it should be the new one tlsCert, err = getCert(nil) require.NoError(t, err) if tlsCert.Leaf == nil { tlsCert.Leaf, err = x509.ParseCertificate(tlsCert.Certificate[0]) require.NoError(t, err) } require.True(t, tlsCert.Leaf.Equal(newCert)) require.True(t, newPriv.Equal(tlsCert.PrivateKey)) require.NoError(t, os.WriteFile(certPath, []byte{'j', 'u', 'n', 'k'}, 0)) timeout := time.After(500 * time.Millisecond) for { if hook.LastEntry() != nil { break } select { case <-timeout: require.FailNow(t, "expected error log entry") default: } } require.Contains(t, hook.LastEntry().Message, "Failed to reload TLS certificates. Using the previously loaded certificates.") } func TestGetOrCreateTLSCertificateBase64(t *testing.T) { certPath, keyPath, cert, priv := testhelpers.GenerateTLSCertificateFilesForTests(t) certPEM, err := os.ReadFile(certPath) require.NoError(t, err) certBase64 := base64.StdEncoding.EncodeToString(certPEM) keyPEM, err := os.ReadFile(keyPath) require.NoError(t, err) keyBase64 := base64.StdEncoding.EncodeToString(keyPEM) logger := logrusx.New("", "") logger.Logger.ExitFunc = func(code int) { t.Fatalf("Logger called os.Exit(%v)", code) } hook := test.NewLocal(logger.Logger) _ = hook cfg := config.MustNew( context.Background(), logger, configx.WithValues(map[string]interface{}{ "dsn": config.DSNMemory, "serve.tls.enabled": true, "serve.tls.cert.base64": certBase64, "serve.tls.key.base64": keyBase64, }), ) d, err := driver.NewRegistryWithoutInit(cfg, logger) require.NoError(t, err) getCert := server.GetOrCreateTLSCertificate(context.Background(), d, config.AdminInterface, nil) require.NotNil(t, getCert) tlsCert, err := getCert(nil) require.NoError(t, err) require.NotNil(t, tlsCert) if tlsCert.Leaf == nil { tlsCert.Leaf, err = x509.ParseCertificate(tlsCert.Certificate[0]) require.NoError(t, err) } require.True(t, tlsCert.Leaf.Equal(cert)) require.True(t, priv.Equal(tlsCert.PrivateKey)) } func TestCreateSelfSignedCertificate(t *testing.T) { keys, err := jwk.GenerateJWK(context.Background(), jose.RS256, uuid.New().String(), "sig") require.NoError(t, err) private := keys.Keys[0] cert, err := tlsx.CreateSelfSignedCertificate(private.Key) require.NoError(t, err) server.AttachCertificate(&private, cert) var actual jose.JSONWebKeySet var b bytes.Buffer require.NoError(t, json.NewEncoder(&b).Encode(keys)) require.NoError(t, json.NewDecoder(&b).Decode(&actual)) }
hydra/cmd/stub/ecdh.key
-----BEGIN EC PRIVATE KEY----- MIGkAgEBBDDvoj/bM1HokUjYWO/IDFs26Jo0GIFtU3tMQQu7ZabKscDMK3dZA0mK v97ij7BBFbCgBwYFK4EEACKhZANiAAT3KhQQCDFN32y/B72g+qOFw/5/aNx1MvZa rwDDa/2G3V0HLTS0VE82sLEUKS8xwkWFI+gNRXk0vvN+Hf+myJI1jOIY+tYQlh+C ZiKGNJ6g5/Su7V6ukGtN+UiY+sx+0LI= -----END EC PRIVATE KEY-----
hydra/cmd/stub/ecdh.pub
-----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE9yoUEAgxTd9svwe9oPqjhcP+f2jcdTL2 Wq8Aw2v9ht1dBy00tFRPNrCxFCkvMcJFhSPoDUV5NL7zfh3/psiSNYziGPrWEJYf gmYihjSeoOf0ru1erpBrTflImPrMftCy -----END PUBLIC KEY-----
JSON
hydra/cmd/stub/jwk.json
{ "kty": "RSA", "n": "slWybuiNYR7uOgKuvaBwqVk8saEutKhOAaW-3hWF65gJei-ZV8QFfYDxs9ZaRZlWAUMtncQPnw7ZQlXO9ogN5cMcN50C6qMOOZzghK7danalhF5lUETC4Hk3Eisbi_PR3IfVyXaRmqL6X66MKj_JAKyD9NFIDVy52K8A198Jojnrw2-XXQW72U68fZtvlyl_BTBWQ9Re5JSTpEcVmpCR8FrFc0RPMBm-G5dRs08vvhZNiTT2JACO5V-J5ZrgP3s5hnGFcQFZgDnXLInDUdoi1MuCjaAU0ta8_08pHMijNix5kFofdPEB954MiZ9k4kQ5_utt02I9x2ssHqw71ojjvw", "e": "AQAB", "d": "GtgNgOZeibUHNRI8TWz-KG-3VCGoDyeafmL9pR5mRz1eh9bsZSqrjOXA_EoS0pEvQgdjsXDWzSGGEJcsDS4TsXc6IyDuVHVw6bk0jqRnzePILHGtHHUNRI7afFCi1-E-wMxtoOLJLhbES2zRynZJgmF1h3-NMf24N-a34MbBA3smLGKjUOPe_AHuSsNj6Z2t7hIVjsZuT1XGQOAuAIsyirnab7Bi58_wJOCkoWkxvb_ImtsuG4nFhmsnep3-hij_3WTq_vGUEoQ6TAPa94aT0OqLxg83FpGS1MSOdlvrJuF7Nq33f5VXGrg56bfAzCi7VJ9etJQq2Az-nYe9_D_voQ", "p": "2fNL9tC8u9M0wjA-kvvtDG96qO6O66Hksssy6RWInD-Iqk3MtHQtLeoCjvX-zERqwOb6SI6empk5pZ9E3_9vJ0dBqkxx3nqn4M_nRWnExGgngJsL959tf50cdxva8y1RjNhT4kCwTrupX_TP8lAG8SfG1Alo2VFR8iWd8hDQcTE", "q": "0XfjEgqAsVh4U0s3lFxKjOepEyp0G1Imty5J16SvcOEAD1Mrmz94aSSp0bYhXNVdbf7nRk77htWC7SE29fGjOzZRS76wxj_SJHF-rktHB2Zt23k1jBeZ4uLMPMnGLY_BJ0995DTGo0yU0rrPbyXosx-ukfQLAHFuggX4RNeM5-8", "dp": "ezNSf4RjC3FKY3LODFwoFV124sNnOr9a_c5rSuKHRHuNj2dHDcKWP1wGcjWQAHu0NLLcS-OCuDVhJsQvNMe5V2SqM8_eljqTZzteqhgtyDBwE_yQ-Tq_tOFk09eFHu1BKfKnCEA06WyfQ8SpP3oJUox_kiB3ilCzl8O30ru6eCE", "dq": "GfJVyEhQxKcG0JqCmfgMrAOOJ_ecRj4Y2Zv8PaACs2LLlRpiTmrASZXnCzkaTNuJJTTsBQOHmJ4eB62Tl0eFRrJlw5ItZ4FEUItWe9SLSdlgRk1vWpkZ0MbzMZx01fP2ox3vpDL9YAD-dlP5mfUCLB4Ci8XFDxr961E9_ZkNtTU", "qi": "HpCgP7B_4GTBe49H0AQueQHBn4RIkgqMy9xiMeR-U-U0vaY0TlfLhnX-5PkNfkPXohXlfL7pxwZNYa6FZhCAubzvhKCdUASivkoGaIEk6g1VTVYS_eDVQ4CAslfl-elXtLq_l1kQ8C14jlHrQzSXx4PQvjDEnAmaHSJNz4mP9Fg", "alg": "RS256", "use": "sig" }
hydra/cmd/stub/pgp.key
-----BEGIN PGP PRIVATE KEY BLOCK----- lQPGBFycM3oBCADUSXgKFJJMXeZbmaYhhK7Ky364MhyBDvh+J8rFdyIC2q4CNzsw e9q+PnOEXuCYlkrtrlHkzaxRUHcva9zFC3zUbKxCa/ErfPFQD6iBheE2L2/Ihp4Z 0PMKIFJM90LRqqa3VqItfleHwT6BUp21mTzq0dZLDUAv36P8IX/N+cMTxxbUuql2 oGZ3AlzPpwwnyOif/vgYEbcK0CcwVO4+jVXQ0xEx6KArv7XZtTcFqF6YslCNVcd2 R6YcAj1DDrIGX2GgacXYlG/hCQe3t9Avog9Qwny6lOTbwCQdfFBp78zAuxgSrru6 ta/HzM+HSnfDTp7rU4tZEdEaJ/Ob0iIEGFV3ABEBAAH+BwMCr0iIUsATVnDol+eM qOA1eOYxyXipVoDHXn8GMLRIDoneay0DWTp+/Z621odo5jrMGDS8z9T9oLFjXmuV k8vyqFU5SCJozsLlCMEg9MXIz1hdhVw09XSIU6Sk5fZm97YCVWYpq7tkL5rIQrFq zzgC7TQtwGXiaHtCW/ir/CiOauPl0lRVTSOL2Olzp5Bcb4bGDXoqopW1OMVMn51V bumwA4oCv5YxxmaGk2EKDb4WdwxZQ7oS5Xnwut7DOWw+8cydAS5kIVcFHseltvZL UzUTiZritqjMDXzgr0HeMcIOg+0MIkb91c/3nlXjMz3Rl2FtfuHm7ZmVZLmamesg 6111p/RekGvBYrhTBNJQD8FhZNcWi9Dn4773t2F3E11BCPT6hw+sQ6fE4tuc4tg0 5H8TIDl+HsETP1WELY5t9dX9sxPMeWV0OLrp7oK7SxM6d5+tfJ3up1sPa+UytKon q2SzzOtXAaKhsiLmAQasFymyDkCZgfx0CXIhdJmdLVGaTkhrZbUQAWUplXgqgFaj oouacgpOibjFu8m48AO3KOqmoRVNKjVH8008+7FEWGa2Ec8Ct9XhiKegkF3oFaCU QA8EsFjV+zmXNHvtbyC5/wNwABICUaZVzLx3RYE9NgFMDDsd2KV61n7fcMmvMKBN OtCxwPGTmVvibWagQOsnv322HF3WSctGfRe5UTV2gcuzuJwQsL2syZYaBuOc70Op xeTIorN9mL0twlmPeXrXXAtKvP1KrpxhuyaiKe/8+IkXiAdPyKY/m0lTsL37swP6 6kvDNmhpeP2V6eq07eNuhK5+NRG+J2sK2l/mCXTzN13mX2W7DHbPPw7vhrvEymsK pWqD7bbmCTJW+qZZzx1Tey4GeuKo0eSVf/iifg/uUf4SbPG+RyKgbYJHRVMGQjL0 06en6ArOW0xutCJoeWRyYSB0ZXN0ZXIgPGV4YW1wbGVAZXhhbXBsZS5jb20+iQFO BBMBCgA4FiEE/jArhaPUtyvCUV4weO7bnWZnI6EFAlycM3oCGwMFCwkIBwMFFQoJ CAsFFgIDAQACHgECF4AACgkQeO7bnWZnI6E+tQgAiVtVXp2/j+P42nFsgWBbnH/Z 2gIxpra+Biu6AVgOPkQD/OceDblCxkZOs9U2XMNwxh7h/cazSkixVFuLx572rcoa amRJqyAGr6sW6f4rn6kf+/qu3u5Q6f1c6Ep0wiDfeOsXSzkojhAgxHGawX/Gvxdc L8HdJClo2hMdl6Kl54K6EdR10hI3+X4C7xZJE4x+O3nKIxquiAeeozsXmT2G+ftd P3O3+PN3d7VRvCRxTIyJIDzn7wttW9UBiLmQyK1mSTJ0atMI9y9zBMj6NHN4ZEuA CVjk+GGtuRdg2k/rkrmms/Vv/ezjNL6vK19Hb8Ah+ziAlyAqLIB6Ej3KkhFtUp0D xgRcnDPgAQgAxxgBUKkeKtam7dgh8kkQnY2st8SfcSq3rOc1q73engZzYYTIcVWq BdmUQvmoN1shWbNP+os2CKj/En1dK1nnFpePol06tjTWbxQARVI7dF2YrdG+pqMZ mQcpYT5TgmHXnp1gU15mGFSL//kkq9KUrB80nztGn5Dp85GrviZzkmZbz7Hic49L O+G+5TTSBEs4uCJFGf9RycwrlP/ytKS/YXFBFbrkI5HWtbfQYcOuDKpt4EodNECG 4NK0xl8CA0mnzAbPl5WLbowxMgu1ItKz3DuSEZegMBI4PccpSojY5QVL4Q/Nvnt2 MDJWl6f7f8dFLxrQEzq8+UDImEFi/yelsQARAQAB/gcDAjt3VX+IWC866JV7XeDL N/7JwIl/G34hyoXwsx4mmo78IFnL5AMDwZexan7FJFQdYsOdKyIfVILzIjTuK0wy IaBDnC7iOOYxRBtm0sJwKRilJg5M6USyG5/1c2brz7w+oA9ML0Esxx/natqIp7pL vuN2p3Z53DfiPpdOOTyH8sWcuAmJR0MO1pY2T6CCEFUFPntD3yzoF0YwbTOHUAA+ UmyXN3M8t/3OszY2rMTZM36eu6N9O9Un++sZLUrzdl5zZK0VOu1exoAgcCSH4xVu psWjrCc5TnH6POL4MFbJBv3B3Ht4UwIScELUqtkR2D/0sEBzFPJ57sdqfq/gLeIl NKcYHgpFFT2BrEstQIvIxJ0NBUlF2azOV/qCM8CG4xWP2j4jvKpaVPBti/HRl76z su8E1e8wMmmb/V2QyPzWf0pSjp6BHIkOegKe9Aj5+bv2tjfpeohwUPp2lP422H0E jxI/na8A/0Orq2+j0xOOa/nTfXUeYq+kTClm62pwGOjrEuycV/qKS4Vv/8dFWwMv qUkXQB7NWdlhzMPz8OrvF1GWZEo+uwpd9pIBPiZeRuWaerTEk1aAerKUA6RU/0Fv hDLYDl8lT9BZ5JBbczaAwkhM3jb1sEnzipczhDr7cb77QDvuLycEOGQb6R9f8m2b sdB4+tO9xXEeANqL84yfZnEDMOW4x0V8+LRjkOY97YcsQG9MJ8jJHV6jOX5BHcB1 wf4oMYR1k3vQV5AFRxE/oDpumStnp0LjkKEzINwc/xuXD4AAlLPKCpNvb9etn40m bemLYhiG1tNk49BsZ+3ZJ212AW2Yx6Stt09YipfKL4UwUyAixMV4d1ayDc+xZERe fiPH6+qTIkRD4QVWl/ZcewvN29gEpl/ptsq6E8g4M3JxmkH9VQRTQEkbMq8M621L G8zCLtZBAYkCbAQYAQoAIBYhBP4wK4Wj1LcrwlFeMHju251mZyOhBQJcnDPgAhsC AUAJEHju251mZyOhwHQgBBkBCgAdFiEE4/sSOIwbqbblVhqUltKxyeOBaJoFAlyc M+AACgkQltKxyeOBaJpVpQf6AhPXOoMPuS95MRZrBsOVYR7JM7quagUjk70fv8pd RBNxRSJQpnFj01SwekaA+4J4rJm0bW+kQcIIQMq+kSVF+u23Bu7FQkUtjzPpM2Pt hFXqIrgmhx5955H+LhNHJZ3qnNOr1/4ysQFrPPQ3RjYZvNC8n9JVDhjsxRizVjmI iMp0rdIpWnj/UdJet/NmZF7iaNJuehw694CYa5hPzBTLybM5BTdzsbbR2xmOC8RE jq+izqIaUuvbJvOk5lVYOhhqNypWq/+GWPtZfeRT9B0HYHsqw40ZnkykMtmwnnhF qtW0IsnwbSu2s1w683E9vkTRyzvA90e76uV/1R/XrX2+sA4/B/9s6EnbTROD4ZIt ouyr1VDn4SeS3knN7bg7DMO3zfpxxKtE1XTP3tqOfP5UQzsz8rLK9SUCpyKuMN4X r1DCQHWTRJSYvUG071u2zaBjkvhSGc/kVFx0ddahvWTAOnYEvFuOZC/XxC6cdJnG DtoSaCPe38SctFmz1IwJd6pULRUaEVotuztFyuQICsDhjZMR4P2AEeBmCOmHvzGN 5fbYt6uEnDBd4tprXCIQfO+yHaCgyN6s5pUXmwUvgcq3Tlbbr1QbJbYvaksojzLK bwlYZjXT5eBn3LYknMZ0yerVN9/fgNDQJ9gHXWSscgmk913Wv01Q1Js2/wNy8+DX El6BJMTjnQPGBFycM/wBCAC45owcWXAvgQwx3TvgiHA7yUnPe6RIJWuUxMwVrA6y bKvqEeip2zZa9euH01feIvIddhzCad0dcwv4cm6GLWWohp1OlbjICMWJWVzywotF +jpS7TW7PG9KGI8POu6lFmKpjDNzy135SiiBMfQYReOk/bUEHN999HOjCYXXZuqD S9Reluq9XleqX3kTqqz67I0eATctmazFF6ftIcXpFpOvkhunbIxCyp+y1KEWWmzr U1PwCd9MxUEHIy4unNa1i++RZuWIv85yWV/+Bzol613TAIUr9N6Yi09z/oA9We46 E3rCXkbTer0iibcXEbhll6WJ7IgJEu6DjtTNFftJO/N3ABEBAAH+BwMCdHZ/OFzu Hr3ohYBiOGszAGD9KOYjdrfTtDN8GQrGn+vzn5Z+itcaegBws8q+CHvYtHoB8YaX erpORsDZmPBogd/bAJBbtzSGecJHrB6P1lqI8WPecEzGOyaYFiWVQyZR0JgR0By/ tBZBqnEgcPBbEb+YsO6X3z+pzBrrkOyv65LV3rVNtadLhMCrcdmdfxjM1XlbKDvH +J1Yh1/YrY8HdHShYFXzJoq2W/JSvDkeTzs71H0ESaSGs1IxCilA9CsxEFEfsDgR 3NsP1NxlYq0VRpk2BtVvnDJRLUmnO/8GaWZxdgWb2ctMui3K3mlSc0b7MThJDpze yaXJ6q2dge2wCToWptqyIQsZFP78pw2Q800YfUmC+Dta4DQYCEkA8SdMR1wM/N2k VrDvyTAbe7lUG+K9LseayteHg5kiz01iAzKGsb+5CwCo7eWoKtmtIoy+AY3hlcJA I/cJ/k3IL4niGjFfEpdNAJzyuI/E32p7hspemUOfLVoQ50W9s34PAeW7EscE9sEg Rbmac6pnMTmkk1CBpBQrQHVE/07PECivX4+NCMH5u5dEp8AVV3IzDHpETOtsOfG9 pAwszI1bGxikmc7k0AF2ZPiLS1w291BIeMVXSOQonsshDEYKVXMY9hmGE13E3v6Y r4eAaouFgA0p6mjYyaS8i7M7Uvz2EfU9dlCxrbDOxrPtuJbMYbZmT4s+dkCyaqS/ wHedCgCqw+e6UEJbUqJe2yYoo568qTm3++bmlZS/Lx9JC4exlbqica6qO5G60MJo HWmnolPwzW+4RYSsbCQSoz3t2K2uSmE0QmbzQYXcwWW04yXIt+L9/t6P0Jmk4XiD ypUJtA1fGqnJB+eF7wuOTXJYI3fsgru9nyDhMr+C0HvIRPyiCQFvrtl5F2DXKuZ+ znh78HA3yPGDKkn4JFHFiQE2BBgBCgAgFiEE/jArhaPUtyvCUV4weO7bnWZnI6EF AlycM/wCGwwACgkQeO7bnWZnI6HErAf/byLABD+UWtygMSG+eJfnL/bBs1VEWQ7I 72BCdO9L50jgK+b8LynNbmUg4pUzeOfmuuuaevkJI0tNgXT/1Ly6x7qdmu6h8mBs TVQxAfTDnZWV7Ib0WziqyO+X7QbuYRNsN6ZidY4WQpVKCevXyLb1lGLssb4ciZXB pW6dijZGI3/zqBGHFsbJBDc5F+bDGU8xK1pj2MZLvDXyaX5r/aJwrl5TKRcYm26v DB2VBQvmIH9SvLmWsd8pzJcEewWthVo1bsSxkpZyTh21NTwNsiYkIdzhEYgFU6BT Tpu9yG7X+ljt0RF7VNrXALbvodD0hxH5FWWlclOeAdxc4OaRsnhLuw== =3JKT -----END PGP PRIVATE KEY BLOCK-----
hydra/cmd/stub/pgp.pub
-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFycM3oBCADUSXgKFJJMXeZbmaYhhK7Ky364MhyBDvh+J8rFdyIC2q4CNzsw e9q+PnOEXuCYlkrtrlHkzaxRUHcva9zFC3zUbKxCa/ErfPFQD6iBheE2L2/Ihp4Z 0PMKIFJM90LRqqa3VqItfleHwT6BUp21mTzq0dZLDUAv36P8IX/N+cMTxxbUuql2 oGZ3AlzPpwwnyOif/vgYEbcK0CcwVO4+jVXQ0xEx6KArv7XZtTcFqF6YslCNVcd2 R6YcAj1DDrIGX2GgacXYlG/hCQe3t9Avog9Qwny6lOTbwCQdfFBp78zAuxgSrru6 ta/HzM+HSnfDTp7rU4tZEdEaJ/Ob0iIEGFV3ABEBAAG0Imh5ZHJhIHRlc3RlciA8 ZXhhbXBsZUBleGFtcGxlLmNvbT6JAU4EEwEKADgWIQT+MCuFo9S3K8JRXjB47tud ZmcjoQUCXJwzegIbAwULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRB47tudZmcj oT61CACJW1Venb+P4/jacWyBYFucf9naAjGmtr4GK7oBWA4+RAP85x4NuULGRk6z 1TZcw3DGHuH9xrNKSLFUW4vHnvatyhpqZEmrIAavqxbp/iufqR/7+q7e7lDp/Vzo SnTCIN946xdLOSiOECDEcZrBf8a/F1wvwd0kKWjaEx2XoqXngroR1HXSEjf5fgLv FkkTjH47ecojGq6IB56jOxeZPYb5+10/c7f483d3tVG8JHFMjIkgPOfvC21b1QGI uZDIrWZJMnRq0wj3L3MEyPo0c3hkS4AJWOT4Ya25F2DaT+uSuaaz9W/97OM0vq8r X0dvwCH7OICXICosgHoSPcqSEW1SuQENBFycM+ABCADHGAFQqR4q1qbt2CHySRCd jay3xJ9xKres5zWrvd6eBnNhhMhxVaoF2ZRC+ag3WyFZs0/6izYIqP8SfV0rWecW l4+iXTq2NNZvFABFUjt0XZit0b6moxmZBylhPlOCYdeenWBTXmYYVIv/+SSr0pSs HzSfO0afkOnzkau+JnOSZlvPseJzj0s74b7lNNIESzi4IkUZ/1HJzCuU//K0pL9h cUEVuuQjkda1t9Bhw64Mqm3gSh00QIbg0rTGXwIDSafMBs+XlYtujDEyC7Ui0rPc O5IRl6AwEjg9xylKiNjlBUvhD82+e3YwMlaXp/t/x0UvGtATOrz5QMiYQWL/J6Wx ABEBAAGJAmwEGAEKACAWIQT+MCuFo9S3K8JRXjB47tudZmcjoQUCXJwz4AIbAgFA CRB47tudZmcjocB0IAQZAQoAHRYhBOP7EjiMG6m25VYalJbSscnjgWiaBQJcnDPg AAoJEJbSscnjgWiaVaUH+gIT1zqDD7kveTEWawbDlWEeyTO6rmoFI5O9H7/KXUQT cUUiUKZxY9NUsHpGgPuCeKyZtG1vpEHCCEDKvpElRfrttwbuxUJFLY8z6TNj7YRV 6iK4JocefeeR/i4TRyWd6pzTq9f+MrEBazz0N0Y2GbzQvJ/SVQ4Y7MUYs1Y5iIjK dK3SKVp4/1HSXrfzZmRe4mjSbnocOveAmGuYT8wUy8mzOQU3c7G20dsZjgvERI6v os6iGlLr2ybzpOZVWDoYajcqVqv/hlj7WX3kU/QdB2B7KsONGZ5MpDLZsJ54RarV tCLJ8G0rtrNcOvNxPb5E0cs7wPdHu+rlf9Uf1619vrAOPwf/bOhJ200Tg+GSLaLs q9VQ5+Enkt5Jze24OwzDt836ccSrRNV0z97ajnz+VEM7M/KyyvUlAqcirjDeF69Q wkB1k0SUmL1BtO9bts2gY5L4UhnP5FRcdHXWob1kwDp2BLxbjmQv18QunHSZxg7a Emgj3t/EnLRZs9SMCXeqVC0VGhFaLbs7RcrkCArA4Y2TEeD9gBHgZgjph78xjeX2 2LerhJwwXeLaa1wiEHzvsh2goMjerOaVF5sFL4HKt05W269UGyW2L2pLKI8yym8J WGY10+XgZ9y2JJzGdMnq1Tff34DQ0CfYB11krHIJpPdd1r9NUNSbNv8DcvPg1xJe gSTE47kBDQRcnDP8AQgAuOaMHFlwL4EMMd074IhwO8lJz3ukSCVrlMTMFawOsmyr 6hHoqds2WvXrh9NX3iLyHXYcwmndHXML+HJuhi1lqIadTpW4yAjFiVlc8sKLRfo6 Uu01uzxvShiPDzrupRZiqYwzc8td+UoogTH0GEXjpP21BBzfffRzowmF12bqg0vU XpbqvV5Xql95E6qs+uyNHgE3LZmsxRen7SHF6RaTr5Ibp2yMQsqfstShFlps61NT 8AnfTMVBByMuLpzWtYvvkWbliL/Ocllf/gc6Jetd0wCFK/TemItPc/6APVnuOhN6 wl5G03q9Iom3FxG4ZZelieyICRLug47UzRX7STvzdwARAQABiQE2BBgBCgAgFiEE /jArhaPUtyvCUV4weO7bnWZnI6EFAlycM/wCGwwACgkQeO7bnWZnI6HErAf/byLA BD+UWtygMSG+eJfnL/bBs1VEWQ7I72BCdO9L50jgK+b8LynNbmUg4pUzeOfmuuua evkJI0tNgXT/1Ly6x7qdmu6h8mBsTVQxAfTDnZWV7Ib0WziqyO+X7QbuYRNsN6Zi dY4WQpVKCevXyLb1lGLssb4ciZXBpW6dijZGI3/zqBGHFsbJBDc5F+bDGU8xK1pj 2MZLvDXyaX5r/aJwrl5TKRcYm26vDB2VBQvmIH9SvLmWsd8pzJcEewWthVo1bsSx kpZyTh21NTwNsiYkIdzhEYgFU6BTTpu9yG7X+ljt0RF7VNrXALbvodD0hxH5FWWl clOeAdxc4OaRsnhLuw== =z+ay -----END PGP PUBLIC KEY BLOCK-----
hydra/cmd/stub/rsa.key
-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAslWybuiNYR7uOgKuvaBwqVk8saEutKhOAaW+3hWF65gJei+Z V8QFfYDxs9ZaRZlWAUMtncQPnw7ZQlXO9ogN5cMcN50C6qMOOZzghK7danalhF5l UETC4Hk3Eisbi/PR3IfVyXaRmqL6X66MKj/JAKyD9NFIDVy52K8A198Jojnrw2+X XQW72U68fZtvlyl/BTBWQ9Re5JSTpEcVmpCR8FrFc0RPMBm+G5dRs08vvhZNiTT2 JACO5V+J5ZrgP3s5hnGFcQFZgDnXLInDUdoi1MuCjaAU0ta8/08pHMijNix5kFof dPEB954MiZ9k4kQ5/utt02I9x2ssHqw71ojjvwIDAQABAoIBABrYDYDmXom1BzUS PE1s/ihvt1QhqA8nmn5i/aUeZkc9XofW7GUqq4zlwPxKEtKRL0IHY7Fw1s0hhhCX LA0uE7F3OiMg7lR1cOm5NI6kZ83jyCxxrRx1DUSO2nxQotfhPsDMbaDiyS4WxEts 0cp2SYJhdYd/jTH9uDfmt+DGwQN7Jixio1Dj3vwB7krDY+mdre4SFY7Gbk9VxkDg LgCLMoq52m+wYufP8CTgpKFpMb2/yJrbLhuJxYZrJ3qd/oYo/91k6v7xlBKEOkwD 2veGk9Dqi8YPNxaRktTEjnZb6ybhezat93+VVxq4Oem3wMwou1SfXrSUKtgM/p2H vfw/76ECgYEA2fNL9tC8u9M0wjA+kvvtDG96qO6O66Hksssy6RWInD+Iqk3MtHQt LeoCjvX+zERqwOb6SI6empk5pZ9E3/9vJ0dBqkxx3nqn4M/nRWnExGgngJsL959t f50cdxva8y1RjNhT4kCwTrupX/TP8lAG8SfG1Alo2VFR8iWd8hDQcTECgYEA0Xfj EgqAsVh4U0s3lFxKjOepEyp0G1Imty5J16SvcOEAD1Mrmz94aSSp0bYhXNVdbf7n Rk77htWC7SE29fGjOzZRS76wxj/SJHF+rktHB2Zt23k1jBeZ4uLMPMnGLY/BJ099 5DTGo0yU0rrPbyXosx+ukfQLAHFuggX4RNeM5+8CgYB7M1J/hGMLcUpjcs4MXCgV XXbiw2c6v1r9zmtK4odEe42PZ0cNwpY/XAZyNZAAe7Q0stxL44K4NWEmxC80x7lX ZKozz96WOpNnO16qGC3IMHAT/JD5Or+04WTT14Ue7UEp8qcIQDTpbJ9DxKk/eglS jH+SIHeKULOXw7fSu7p4IQKBgBnyVchIUMSnBtCagpn4DKwDjif3nEY+GNmb/D2g ArNiy5UaYk5qwEmV5ws5GkzbiSU07AUDh5ieHgetk5dHhUayZcOSLWeBRFCLVnvU i0nZYEZNb1qZGdDG8zGcdNXz9qMd76Qy/WAA/nZT+Zn1AiweAovFxQ8a/etRPf2Z DbU1AoGAHpCgP7B/4GTBe49H0AQueQHBn4RIkgqMy9xiMeR+U+U0vaY0TlfLhnX+ 5PkNfkPXohXlfL7pxwZNYa6FZhCAubzvhKCdUASivkoGaIEk6g1VTVYS/eDVQ4CA slfl+elXtLq/l1kQ8C14jlHrQzSXx4PQvjDEnAmaHSJNz4mP9Fg= -----END RSA PRIVATE KEY-----
hydra/cmd/stub/rsa.pub
-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAslWybuiNYR7uOgKuvaBw qVk8saEutKhOAaW+3hWF65gJei+ZV8QFfYDxs9ZaRZlWAUMtncQPnw7ZQlXO9ogN 5cMcN50C6qMOOZzghK7danalhF5lUETC4Hk3Eisbi/PR3IfVyXaRmqL6X66MKj/J AKyD9NFIDVy52K8A198Jojnrw2+XXQW72U68fZtvlyl/BTBWQ9Re5JSTpEcVmpCR 8FrFc0RPMBm+G5dRs08vvhZNiTT2JACO5V+J5ZrgP3s5hnGFcQFZgDnXLInDUdoi 1MuCjaAU0ta8/08pHMijNix5kFofdPEB954MiZ9k4kQ5/utt02I9x2ssHqw71ojj vwIDAQAB -----END PUBLIC KEY-----
JSON
hydra/cmd/test/another_public_key.json
{ "kty": "RSA", "e": "AQAB", "use": "sig", "kid": "public:8a5ff76a-6766-11ea-bc55-0242ac130003S", "alg": "RS256", "n": "l80jJJqcc1PpefIGVIjuPvA1D7NscnuF9aQqLa7I9rDUK4IaSOO3kL_EF13k-jTzcA5q4OZn5dR0kmqIMZT2gQ" }
JSON
hydra/cmd/test/private_key.json
{ "kty": "RSA", "e": "AQAB", "use": "sig", "kid": "private:7a5ff76a-6766-11ea-bc55-0242ac130003S", "alg": "RS256", "n": "l80jJJqcc1PpefIGVIjuPvA1D7NscnuF9aQqLa7I9rDUK4IaSOO3kL_EF13k-jTzcA5q4OZn5dR0kmqIMZT2gQ" }
JSON
hydra/cmd/test/public_key.json
{ "kty": "RSA", "e": "AQAB", "use": "sig", "kid": "public:7a5ff76a-6766-11ea-bc55-0242ac130003S", "alg": "RS256", "n": "l80jJJqcc1PpefIGVIjuPvA1D7NscnuF9aQqLa7I9rDUK4IaSOO3kL_EF13k-jTzcA5q4OZn5dR0kmqIMZT2gQ" }
Go
hydra/consent/handler.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "encoding/json" "net/http" "net/url" "time" "github.com/ory/hydra/v2/flow" "github.com/ory/hydra/v2/oauth2/flowctx" "github.com/ory/hydra/v2/x/events" "github.com/ory/x/pagination/tokenpagination" "github.com/ory/x/httprouterx" "github.com/julienschmidt/httprouter" "github.com/pkg/errors" "github.com/ory/fosite" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/x" "github.com/ory/x/errorsx" "github.com/ory/x/sqlxx" "github.com/ory/x/stringsx" "github.com/ory/x/urlx" ) type Handler struct { r InternalRegistry c *config.DefaultProvider } const ( LoginPath = "/oauth2/auth/requests/login" ConsentPath = "/oauth2/auth/requests/consent" LogoutPath = "/oauth2/auth/requests/logout" SessionsPath = "/oauth2/auth/sessions" ) func NewHandler( r InternalRegistry, c *config.DefaultProvider, ) *Handler { return &Handler{ c: c, r: r, } } func (h *Handler) SetRoutes(admin *httprouterx.RouterAdmin) { admin.GET(LoginPath, h.getOAuth2LoginRequest) admin.PUT(LoginPath+"/accept", h.acceptOAuth2LoginRequest) admin.PUT(LoginPath+"/reject", h.rejectOAuth2LoginRequest) admin.GET(ConsentPath, h.getOAuth2ConsentRequest) admin.PUT(ConsentPath+"/accept", h.acceptOAuth2ConsentRequest) admin.PUT(ConsentPath+"/reject", h.rejectOAuth2ConsentRequest) admin.DELETE(SessionsPath+"/login", h.revokeOAuth2LoginSessions) admin.GET(SessionsPath+"/consent", h.listOAuth2ConsentSessions) admin.DELETE(SessionsPath+"/consent", h.revokeOAuth2ConsentSessions) admin.GET(LogoutPath, h.getOAuth2LogoutRequest) admin.PUT(LogoutPath+"/accept", h.acceptOAuth2LogoutRequest) admin.PUT(LogoutPath+"/reject", h.rejectOAuth2LogoutRequest) } // Revoke OAuth 2.0 Consent Session Parameters // // swagger:parameters revokeOAuth2ConsentSessions // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type revokeOAuth2ConsentSessions struct { // OAuth 2.0 Consent Subject // // The subject whose consent sessions should be deleted. // // in: query // required: true Subject string `json:"subject"` // OAuth 2.0 Client ID // // If set, deletes only those consent sessions that have been granted to the specified OAuth 2.0 Client ID. // // in: query Client string `json:"client"` // Revoke All Consent Sessions // // If set to `true` deletes all consent sessions by the Subject that have been granted. // // in: query All bool `json:"all"` } // swagger:route DELETE /admin/oauth2/auth/sessions/consent oAuth2 revokeOAuth2ConsentSessions // // # Revoke OAuth 2.0 Consent Sessions of a Subject // // This endpoint revokes a subject's granted consent sessions and invalidates all // associated OAuth 2.0 Access Tokens. You may also only revoke sessions for a specific OAuth 2.0 Client ID. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 204: emptyResponse // default: errorOAuth2 func (h *Handler) revokeOAuth2ConsentSessions(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { subject := r.URL.Query().Get("subject") client := r.URL.Query().Get("client") allClients := r.URL.Query().Get("all") == "true" if subject == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'subject' is not defined but should have been.`))) return } switch { case len(client) > 0: if err := h.r.ConsentManager().RevokeSubjectClientConsentSession(r.Context(), subject, client); err != nil && !errors.Is(err, x.ErrNotFound) { h.r.Writer().WriteError(w, r, err) return } events.Trace(r.Context(), events.ConsentRevoked, events.WithSubject(subject), events.WithClientID(client)) case allClients: if err := h.r.ConsentManager().RevokeSubjectConsentSession(r.Context(), subject); err != nil && !errors.Is(err, x.ErrNotFound) { h.r.Writer().WriteError(w, r, err) return } events.Trace(r.Context(), events.ConsentRevoked, events.WithSubject(subject)) default: h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter both 'client' and 'all' is not defined but one of them should have been.`))) return } w.WriteHeader(http.StatusNoContent) } // List OAuth 2.0 Consent Session Parameters // // swagger:parameters listOAuth2ConsentSessions // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type listOAuth2ConsentSessions struct { tokenpagination.RequestParameters // The subject to list the consent sessions for. // // in: query // required: true Subject string `json:"subject"` // The login session id to list the consent sessions for. // // in: query // required: false LoginSessionId string `json:"login_session_id"` } // swagger:route GET /admin/oauth2/auth/sessions/consent oAuth2 listOAuth2ConsentSessions // // # List OAuth 2.0 Consent Sessions of a Subject // // This endpoint lists all subject's granted consent sessions, including client and granted scope. // If the subject is unknown or has not granted any consent sessions yet, the endpoint returns an // empty JSON array with status code 200 OK. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2ConsentSessions // default: errorOAuth2 func (h *Handler) listOAuth2ConsentSessions(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { subject := r.URL.Query().Get("subject") if subject == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'subject' is not defined but should have been.`))) return } loginSessionId := r.URL.Query().Get("login_session_id") page, itemsPerPage := x.ParsePagination(r) var s []flow.AcceptOAuth2ConsentRequest var err error if len(loginSessionId) == 0 { s, err = h.r.ConsentManager().FindSubjectsGrantedConsentRequests(r.Context(), subject, itemsPerPage, itemsPerPage*page) } else { s, err = h.r.ConsentManager().FindSubjectsSessionGrantedConsentRequests(r.Context(), subject, loginSessionId, itemsPerPage, itemsPerPage*page) } if errors.Is(err, ErrNoPreviousConsentFound) { h.r.Writer().Write(w, r, []flow.OAuth2ConsentSession{}) return } else if err != nil { h.r.Writer().WriteError(w, r, err) return } var a []flow.OAuth2ConsentSession for _, session := range s { session.ConsentRequest.Client = sanitizeClient(session.ConsentRequest.Client) a = append(a, flow.OAuth2ConsentSession(session)) } if len(a) == 0 { a = []flow.OAuth2ConsentSession{} } n, err := h.r.ConsentManager().CountSubjectsGrantedConsentRequests(r.Context(), subject) if err != nil { h.r.Writer().WriteError(w, r, err) return } x.PaginationHeader(w, r.URL, int64(n), itemsPerPage, itemsPerPage*page) h.r.Writer().Write(w, r, a) } // Revoke OAuth 2.0 Consent Login Sessions Parameters // // swagger:parameters revokeOAuth2LoginSessions // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type revokeOAuth2LoginSessions struct { // OAuth 2.0 Subject // // The subject to revoke authentication sessions for. // // in: query Subject string `json:"subject"` // OAuth 2.0 Subject // // The subject to revoke authentication sessions for. // // in: query SessionID string `json:"sid"` } // swagger:route DELETE /admin/oauth2/auth/sessions/login oAuth2 revokeOAuth2LoginSessions // // # Revokes OAuth 2.0 Login Sessions by either a Subject or a SessionID // // This endpoint invalidates authentication sessions. After revoking the authentication session(s), the subject // has to re-authenticate at the Ory OAuth2 Provider. This endpoint does not invalidate any tokens. // // If you send the subject in a query param, all authentication sessions that belong to that subject are revoked. // No OpennID Connect Front- or Back-channel logout is performed in this case. // // Alternatively, you can send a SessionID via `sid` query param, in which case, only the session that is connected // to that SessionID is revoked. OpenID Connect Back-channel logout is performed in this case. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 204: emptyResponse // default: errorOAuth2 func (h *Handler) revokeOAuth2LoginSessions(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { sid := r.URL.Query().Get("sid") subject := r.URL.Query().Get("subject") if sid == "" && subject == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Either 'subject' or 'sid' query parameters need to be defined.`))) return } if sid != "" { if err := h.r.ConsentStrategy().HandleHeadlessLogout(r.Context(), w, r, sid); err != nil { h.r.Writer().WriteError(w, r, err) return } w.WriteHeader(http.StatusNoContent) return } if err := h.r.ConsentManager().RevokeSubjectLoginSession(r.Context(), subject); err != nil { h.r.Writer().WriteError(w, r, err) return } w.WriteHeader(http.StatusNoContent) } // Get OAuth 2.0 Login Request // // swagger:parameters getOAuth2LoginRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type getOAuth2LoginRequest struct { // OAuth 2.0 Login Request Challenge // // in: query // required: true Challenge string `json:"login_challenge"` } // swagger:route GET /admin/oauth2/auth/requests/login oAuth2 getOAuth2LoginRequest // // # Get OAuth 2.0 Login Request // // When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, Ory asks the login provider // to authenticate the subject and then tell the Ory OAuth2 Service about it. // // Per default, the login provider is Ory itself. You may use a different login provider which needs to be a web-app // you write and host, and it must be able to authenticate ("show the subject a login screen") // a subject (in OAuth2 the proper name for subject is "resource owner"). // // The authentication challenge is appended to the login provider URL to which the subject's user-agent (browser) is redirected to. The login // provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2LoginRequest // 410: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) getOAuth2LoginRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { challenge := stringsx.Coalesce( r.URL.Query().Get("login_challenge"), r.URL.Query().Get("challenge"), ) if challenge == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'challenge' is not defined but should have been.`))) return } request, err := h.r.ConsentManager().GetLoginRequest(r.Context(), challenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } if request.WasHandled { h.r.Writer().WriteCode(w, r, http.StatusGone, &flow.OAuth2RedirectTo{ RedirectTo: request.RequestURL, }) return } request.Client = sanitizeClient(request.Client) h.r.Writer().Write(w, r, request) } // Accept OAuth 2.0 Login Request // // swagger:parameters acceptOAuth2LoginRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type acceptOAuth2LoginRequest struct { // OAuth 2.0 Login Request Challenge // // in: query // required: true Challenge string `json:"login_challenge"` // in: body Body flow.HandledLoginRequest } // swagger:route PUT /admin/oauth2/auth/requests/login/accept oAuth2 acceptOAuth2LoginRequest // // # Accept OAuth 2.0 Login Request // // When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, Ory asks the login provider // to authenticate the subject and then tell the Ory OAuth2 Service about it. // // The authentication challenge is appended to the login provider URL to which the subject's user-agent (browser) is redirected to. The login // provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. // // This endpoint tells Ory that the subject has successfully authenticated and includes additional information such as // the subject's ID and if Ory should remember the subject's subject agent for future authentication attempts by setting // a cookie. // // The response contains a redirect URL which the login provider should redirect the user-agent to. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) acceptOAuth2LoginRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { ctx := r.Context() challenge := stringsx.Coalesce( r.URL.Query().Get("login_challenge"), r.URL.Query().Get("challenge"), ) if challenge == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'challenge' is not defined but should have been.`))) return } var p flow.HandledLoginRequest d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if err := d.Decode(&p); err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithWrap(err).WithHintf("Unable to decode body because: %s", err))) return } if p.Subject == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Field 'subject' must not be empty."))) return } p.ID = challenge ar, err := h.r.ConsentManager().GetLoginRequest(ctx, challenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } else if ar.Subject != "" && p.Subject != ar.Subject { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Field 'subject' does not match subject from previous authentication."))) return } if ar.Skip { p.Remember = true // If skip is true remember is also true to allow consecutive calls as the same user! p.AuthenticatedAt = ar.AuthenticatedAt } else { p.AuthenticatedAt = sqlxx.NullTime(time.Now().UTC(). // Rounding is important to avoid SQL time synchronization issues in e.g. MySQL! Truncate(time.Second)) ar.AuthenticatedAt = p.AuthenticatedAt } p.RequestedAt = ar.RequestedAt f, err := flowctx.Decode[flow.Flow](ctx, h.r.FlowCipher(), challenge, flowctx.AsLoginChallenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } request, err := h.r.ConsentManager().HandleLoginRequest(ctx, f, challenge, &p) if err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(err)) return } ru, err := url.Parse(request.RequestURL) if err != nil { h.r.Writer().WriteError(w, r, err) return } verifier, err := f.ToLoginVerifier(ctx, h.r) if err != nil { h.r.Writer().WriteError(w, r, err) return } events.Trace(ctx, events.LoginAccepted, events.WithClientID(request.Client.GetID()), events.WithSubject(request.Subject)) h.r.Writer().Write(w, r, &flow.OAuth2RedirectTo{ RedirectTo: urlx.SetQuery(ru, url.Values{"login_verifier": {verifier}}).String(), }) } // Reject OAuth 2.0 Login Request // // swagger:parameters rejectOAuth2LoginRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type rejectOAuth2LoginRequest struct { // OAuth 2.0 Login Request Challenge // // in: query // required: true Challenge string `json:"login_challenge"` // in: body Body flow.RequestDeniedError } // swagger:route PUT /admin/oauth2/auth/requests/login/reject oAuth2 rejectOAuth2LoginRequest // // # Reject OAuth 2.0 Login Request // // When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, Ory asks the login provider // to authenticate the subject and then tell the Ory OAuth2 Service about it. // // The authentication challenge is appended to the login provider URL to which the subject's user-agent (browser) is redirected to. The login // provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. // // This endpoint tells Ory that the subject has not authenticated and includes a reason why the authentication // was denied. // // The response contains a redirect URL which the login provider should redirect the user-agent to. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) rejectOAuth2LoginRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { ctx := r.Context() challenge := stringsx.Coalesce( r.URL.Query().Get("login_challenge"), r.URL.Query().Get("challenge"), ) if challenge == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'challenge' is not defined but should have been.`))) return } var p flow.RequestDeniedError d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if err := d.Decode(&p); err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithWrap(err).WithHintf("Unable to decode body because: %s", err))) return } p.Valid = true p.SetDefaults(flow.LoginRequestDeniedErrorName) ar, err := h.r.ConsentManager().GetLoginRequest(ctx, challenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } f, err := flowctx.Decode[flow.Flow](ctx, h.r.FlowCipher(), challenge, flowctx.AsLoginChallenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } request, err := h.r.ConsentManager().HandleLoginRequest(ctx, f, challenge, &flow.HandledLoginRequest{ Error: &p, ID: challenge, RequestedAt: ar.RequestedAt, }) if err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(err)) return } verifier, err := f.ToLoginVerifier(ctx, h.r) if err != nil { h.r.Writer().WriteError(w, r, err) return } ru, err := url.Parse(request.RequestURL) if err != nil { h.r.Writer().WriteError(w, r, err) return } events.Trace(ctx, events.LoginRejected, events.WithClientID(request.Client.GetID()), events.WithSubject(request.Subject)) h.r.Writer().Write(w, r, &flow.OAuth2RedirectTo{ RedirectTo: urlx.SetQuery(ru, url.Values{"login_verifier": {verifier}}).String(), }) } // Get OAuth 2.0 Consent Request // // swagger:parameters getOAuth2ConsentRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type getOAuth2ConsentRequest struct { // OAuth 2.0 Consent Request Challenge // // in: query // required: true Challenge string `json:"consent_challenge"` } // swagger:route GET /admin/oauth2/auth/requests/consent oAuth2 getOAuth2ConsentRequest // // # Get OAuth 2.0 Consent Request // // When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, Ory asks the login provider // to authenticate the subject and then tell Ory now about it. If the subject authenticated, he/she must now be asked if // the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the subject's behalf. // // The consent challenge is appended to the consent provider's URL to which the subject's user-agent (browser) is redirected to. The consent // provider uses that challenge to fetch information on the OAuth2 request and then tells Ory if the subject accepted // or rejected the request. // // The default consent provider is available via the Ory Managed Account Experience. To customize the consent provider, please // head over to the OAuth 2.0 documentation. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2ConsentRequest // 410: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) getOAuth2ConsentRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { challenge := stringsx.Coalesce( r.URL.Query().Get("consent_challenge"), r.URL.Query().Get("challenge"), ) if challenge == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'challenge' is not defined but should have been.`))) return } request, err := h.r.ConsentManager().GetConsentRequest(r.Context(), challenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } if request.WasHandled { h.r.Writer().WriteCode(w, r, http.StatusGone, &flow.OAuth2RedirectTo{ RedirectTo: request.RequestURL, }) return } if request.RequestedScope == nil { request.RequestedScope = []string{} } if request.RequestedAudience == nil { request.RequestedAudience = []string{} } request.Client = sanitizeClient(request.Client) h.r.Writer().Write(w, r, request) } // Accept OAuth 2.0 Consent Request // // swagger:parameters acceptOAuth2ConsentRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type acceptOAuth2ConsentRequest struct { // OAuth 2.0 Consent Request Challenge // // in: query // required: true Challenge string `json:"consent_challenge"` // in: body Body flow.AcceptOAuth2ConsentRequest } // swagger:route PUT /admin/oauth2/auth/requests/consent/accept oAuth2 acceptOAuth2ConsentRequest // // # Accept OAuth 2.0 Consent Request // // When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, Ory asks the login provider // to authenticate the subject and then tell Ory now about it. If the subject authenticated, he/she must now be asked if // the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the subject's behalf. // // The consent challenge is appended to the consent provider's URL to which the subject's user-agent (browser) is redirected to. The consent // provider uses that challenge to fetch information on the OAuth2 request and then tells Ory if the subject accepted // or rejected the request. // // This endpoint tells Ory that the subject has authorized the OAuth 2.0 client to access resources on his/her behalf. // The consent provider includes additional information, such as session data for access and ID tokens, and if the // consent request should be used as basis for future requests. // // The response contains a redirect URL which the consent provider should redirect the user-agent to. // // The default consent provider is available via the Ory Managed Account Experience. To customize the consent provider, please // head over to the OAuth 2.0 documentation. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) acceptOAuth2ConsentRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { ctx := r.Context() challenge := stringsx.Coalesce( r.URL.Query().Get("consent_challenge"), r.URL.Query().Get("challenge"), ) if challenge == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'challenge' is not defined but should have been.`))) return } var p flow.AcceptOAuth2ConsentRequest d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if err := d.Decode(&p); err != nil { h.r.Writer().WriteErrorCode(w, r, http.StatusBadRequest, errorsx.WithStack(err)) return } cr, err := h.r.ConsentManager().GetConsentRequest(ctx, challenge) if err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(err)) return } p.ID = challenge p.RequestedAt = cr.RequestedAt p.HandledAt = sqlxx.NullTime(time.Now().UTC()) f, err := flowctx.Decode[flow.Flow](ctx, h.r.FlowCipher(), challenge, flowctx.AsConsentChallenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } hr, err := h.r.ConsentManager().HandleConsentRequest(ctx, f, &p) if err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(err)) return } else if hr.Skip { p.Remember = false } ru, err := url.Parse(hr.RequestURL) if err != nil { h.r.Writer().WriteError(w, r, err) return } verifier, err := f.ToConsentVerifier(ctx, h.r) if err != nil { h.r.Writer().WriteError(w, r, err) return } events.Trace(ctx, events.ConsentAccepted, events.WithClientID(cr.Client.GetID()), events.WithSubject(cr.Subject)) h.r.Writer().Write(w, r, &flow.OAuth2RedirectTo{ RedirectTo: urlx.SetQuery(ru, url.Values{"consent_verifier": {verifier}}).String(), }) } // Reject OAuth 2.0 Consent Request // // swagger:parameters rejectOAuth2ConsentRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type adminRejectOAuth2ConsentRequest struct { // OAuth 2.0 Consent Request Challenge // // in: query // required: true Challenge string `json:"consent_challenge"` // in: body Body flow.RequestDeniedError } // swagger:route PUT /admin/oauth2/auth/requests/consent/reject oAuth2 rejectOAuth2ConsentRequest // // # Reject OAuth 2.0 Consent Request // // When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, Ory asks the login provider // to authenticate the subject and then tell Ory now about it. If the subject authenticated, he/she must now be asked if // the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the subject's behalf. // // The consent challenge is appended to the consent provider's URL to which the subject's user-agent (browser) is redirected to. The consent // provider uses that challenge to fetch information on the OAuth2 request and then tells Ory if the subject accepted // or rejected the request. // // This endpoint tells Ory that the subject has not authorized the OAuth 2.0 client to access resources on his/her behalf. // The consent provider must include a reason why the consent was not granted. // // The response contains a redirect URL which the consent provider should redirect the user-agent to. // // The default consent provider is available via the Ory Managed Account Experience. To customize the consent provider, please // head over to the OAuth 2.0 documentation. // // Consumes: // - application/json // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) rejectOAuth2ConsentRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { ctx := r.Context() challenge := stringsx.Coalesce( r.URL.Query().Get("consent_challenge"), r.URL.Query().Get("challenge"), ) if challenge == "" { h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(`Query parameter 'challenge' is not defined but should have been.`))) return } var p flow.RequestDeniedError d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if err := d.Decode(&p); err != nil { h.r.Writer().WriteErrorCode(w, r, http.StatusBadRequest, errorsx.WithStack(err)) return } p.Valid = true p.SetDefaults(flow.ConsentRequestDeniedErrorName) hr, err := h.r.ConsentManager().GetConsentRequest(ctx, challenge) if err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(err)) return } f, err := flowctx.Decode[flow.Flow](ctx, h.r.FlowCipher(), challenge, flowctx.AsConsentChallenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } request, err := h.r.ConsentManager().HandleConsentRequest(ctx, f, &flow.AcceptOAuth2ConsentRequest{ Error: &p, ID: challenge, RequestedAt: hr.RequestedAt, HandledAt: sqlxx.NullTime(time.Now().UTC()), }) if err != nil { h.r.Writer().WriteError(w, r, errorsx.WithStack(err)) return } ru, err := url.Parse(request.RequestURL) if err != nil { h.r.Writer().WriteError(w, r, err) return } verifier, err := f.ToConsentVerifier(ctx, h.r) if err != nil { h.r.Writer().WriteError(w, r, err) return } events.Trace(ctx, events.ConsentRejected, events.WithClientID(request.Client.GetID()), events.WithSubject(request.Subject)) h.r.Writer().Write(w, r, &flow.OAuth2RedirectTo{ RedirectTo: urlx.SetQuery(ru, url.Values{"consent_verifier": {verifier}}).String(), }) } // Accept OAuth 2.0 Logout Request // // swagger:parameters acceptOAuth2LogoutRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type acceptOAuth2LogoutRequest struct { // OAuth 2.0 Logout Request Challenge // // in: query // required: true Challenge string `json:"logout_challenge"` } // swagger:route PUT /admin/oauth2/auth/requests/logout/accept oAuth2 acceptOAuth2LogoutRequest // // # Accept OAuth 2.0 Session Logout Request // // When a user or an application requests Ory OAuth 2.0 to remove the session state of a subject, this endpoint is used to confirm that logout request. // // The response contains a redirect URL which the consent provider should redirect the user-agent to. // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) acceptOAuth2LogoutRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { challenge := stringsx.Coalesce( r.URL.Query().Get("logout_challenge"), r.URL.Query().Get("challenge"), ) c, err := h.r.ConsentManager().AcceptLogoutRequest(r.Context(), challenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } h.r.Writer().Write(w, r, &flow.OAuth2RedirectTo{ RedirectTo: urlx.SetQuery(urlx.AppendPaths(h.c.PublicURL(r.Context()), "/oauth2/sessions/logout"), url.Values{"logout_verifier": {c.Verifier}}).String(), }) } // Reject OAuth 2.0 Logout Request // // swagger:parameters rejectOAuth2LogoutRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type rejectOAuth2LogoutRequest struct { // in: query // required: true Challenge string `json:"logout_challenge"` } // swagger:route PUT /admin/oauth2/auth/requests/logout/reject oAuth2 rejectOAuth2LogoutRequest // // # Reject OAuth 2.0 Session Logout Request // // When a user or an application requests Ory OAuth 2.0 to remove the session state of a subject, this endpoint is used to deny that logout request. // No HTTP request body is required. // // The response is empty as the logout provider has to chose what action to perform next. // // Produces: // - application/json // // Schemes: http, https // // Responses: // 204: emptyResponse // default: errorOAuth2 func (h *Handler) rejectOAuth2LogoutRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { challenge := stringsx.Coalesce( r.URL.Query().Get("logout_challenge"), r.URL.Query().Get("challenge"), ) if err := h.r.ConsentManager().RejectLogoutRequest(r.Context(), challenge); err != nil { h.r.Writer().WriteError(w, r, err) return } w.WriteHeader(http.StatusNoContent) } // Get OAuth 2.0 Logout Request // // swagger:parameters getOAuth2LogoutRequest // //lint:ignore U1000 Used to generate Swagger and OpenAPI definitions type getOAuth2LogoutRequest struct { // in: query // required: true Challenge string `json:"logout_challenge"` } // swagger:route GET /admin/oauth2/auth/requests/logout oAuth2 getOAuth2LogoutRequest // // # Get OAuth 2.0 Session Logout Request // // Use this endpoint to fetch an Ory OAuth 2.0 logout request. // // Produces: // - application/json // // Schemes: http, https // // Responses: // 200: oAuth2LogoutRequest // 410: oAuth2RedirectTo // default: errorOAuth2 func (h *Handler) getOAuth2LogoutRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { challenge := stringsx.Coalesce( r.URL.Query().Get("logout_challenge"), r.URL.Query().Get("challenge"), ) request, err := h.r.ConsentManager().GetLogoutRequest(r.Context(), challenge) if err != nil { h.r.Writer().WriteError(w, r, err) return } // We do not want to share the secret so remove it. if request.Client != nil { request.Client.Secret = "" } if request.WasHandled { h.r.Writer().WriteCode(w, r, http.StatusGone, &flow.OAuth2RedirectTo{ RedirectTo: request.RequestURL, }) return } h.r.Writer().Write(w, r, request) }
Go
hydra/consent/handler_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent_test import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/require" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/client" . "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/flow" "github.com/ory/hydra/v2/internal" "github.com/ory/hydra/v2/x" "github.com/ory/x/contextx" "github.com/ory/x/pointerx" "github.com/ory/x/sqlxx" ) func TestGetLogoutRequest(t *testing.T) { for k, tc := range []struct { exists bool handled bool status int }{ {false, false, http.StatusNotFound}, {true, false, http.StatusOK}, {true, true, http.StatusGone}, } { t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { ctx := context.Background() key := fmt.Sprint(k) challenge := "challenge" + key requestURL := "http://192.0.2.1" conf := internal.NewConfigurationWithDefaults() reg := internal.NewRegistryMemory(t, conf, &contextx.Default{}) if tc.exists { cl := &client.Client{LegacyClientID: "client" + key} require.NoError(t, reg.ClientManager().CreateClient(ctx, cl)) require.NoError(t, reg.ConsentManager().CreateLogoutRequest(context.TODO(), &flow.LogoutRequest{ Client: cl, ID: challenge, WasHandled: tc.handled, RequestURL: requestURL, })) } h := NewHandler(reg, conf) r := x.NewRouterAdmin(conf.AdminURL) h.SetRoutes(r) ts := httptest.NewServer(r) defer ts.Close() c := &http.Client{} resp, err := c.Get(ts.URL + "/admin" + LogoutPath + "?challenge=" + challenge) require.NoError(t, err) require.EqualValues(t, tc.status, resp.StatusCode) if tc.handled { var result flow.OAuth2RedirectTo require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.Equal(t, requestURL, result.RedirectTo) } else if tc.exists { var result flow.LogoutRequest require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.Equal(t, challenge, result.ID) require.Equal(t, requestURL, result.RequestURL) } }) } } func TestGetLoginRequest(t *testing.T) { for k, tc := range []struct { exists bool handled bool status int }{ {false, false, http.StatusNotFound}, {true, false, http.StatusOK}, {true, true, http.StatusGone}, } { t.Run(fmt.Sprintf("exists=%v/handled=%v", tc.exists, tc.handled), func(t *testing.T) { ctx := context.Background() key := fmt.Sprint(k) challenge := "challenge" + key requestURL := "http://192.0.2.1" conf := internal.NewConfigurationWithDefaults() reg := internal.NewRegistryMemory(t, conf, &contextx.Default{}) if tc.exists { cl := &client.Client{LegacyClientID: "client" + key} require.NoError(t, reg.ClientManager().CreateClient(context.Background(), cl)) f, err := reg.ConsentManager().CreateLoginRequest(context.Background(), &flow.LoginRequest{ Client: cl, ID: challenge, RequestURL: requestURL, RequestedAt: time.Now(), }) require.NoError(t, err) challenge, err = f.ToLoginChallenge(ctx, reg) require.NoError(t, err) if tc.handled { _, err := reg.ConsentManager().HandleLoginRequest(ctx, f, challenge, &flow.HandledLoginRequest{ID: challenge, WasHandled: true}) require.NoError(t, err) challenge, err = f.ToLoginChallenge(ctx, reg) require.NoError(t, err) } } h := NewHandler(reg, conf) r := x.NewRouterAdmin(conf.AdminURL) h.SetRoutes(r) ts := httptest.NewServer(r) defer ts.Close() c := &http.Client{} resp, err := c.Get(ts.URL + "/admin" + LoginPath + "?challenge=" + challenge) require.NoError(t, err) require.EqualValues(t, tc.status, resp.StatusCode) if tc.handled { var result flow.OAuth2RedirectTo require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.Equal(t, requestURL, result.RedirectTo) } else if tc.exists { var result flow.LoginRequest require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.Equal(t, challenge, result.ID) require.Equal(t, requestURL, result.RequestURL) require.NotNil(t, result.Client) } }) } } func TestGetConsentRequest(t *testing.T) { for k, tc := range []struct { exists bool handled bool status int }{ {false, false, http.StatusNotFound}, {true, false, http.StatusOK}, {true, true, http.StatusGone}, } { t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { ctx := context.Background() key := fmt.Sprint(k) challenge := "challenge" + key requestURL := "http://192.0.2.1" conf := internal.NewConfigurationWithDefaults() reg := internal.NewRegistryMemory(t, conf, &contextx.Default{}) if tc.exists { cl := &client.Client{LegacyClientID: "client" + key} require.NoError(t, reg.ClientManager().CreateClient(ctx, cl)) lr := &flow.LoginRequest{ ID: "login-" + challenge, Client: cl, RequestURL: requestURL, RequestedAt: time.Now(), } f, err := reg.ConsentManager().CreateLoginRequest(ctx, lr) require.NoError(t, err) challenge, err = f.ToLoginChallenge(ctx, reg) require.NoError(t, err) _, err = reg.ConsentManager().HandleLoginRequest(ctx, f, challenge, &flow.HandledLoginRequest{ ID: challenge, }) require.NoError(t, err) challenge, err = f.ToConsentChallenge(ctx, reg) require.NoError(t, err) require.NoError(t, reg.ConsentManager().CreateConsentRequest(ctx, f, &flow.OAuth2ConsentRequest{ Client: cl, ID: challenge, Verifier: challenge, CSRF: challenge, LoginChallenge: sqlxx.NullString(lr.ID), })) if tc.handled { _, err := reg.ConsentManager().HandleConsentRequest(ctx, f, &flow.AcceptOAuth2ConsentRequest{ ID: challenge, WasHandled: true, HandledAt: sqlxx.NullTime(time.Now()), }) require.NoError(t, err) challenge, err = f.ToConsentChallenge(ctx, reg) require.NoError(t, err) } } h := NewHandler(reg, conf) r := x.NewRouterAdmin(conf.AdminURL) h.SetRoutes(r) ts := httptest.NewServer(r) defer ts.Close() c := &http.Client{} resp, err := c.Get(ts.URL + "/admin" + ConsentPath + "?challenge=" + challenge) require.NoError(t, err) require.EqualValues(t, tc.status, resp.StatusCode) if tc.handled { var result flow.OAuth2RedirectTo require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.Equal(t, requestURL, result.RedirectTo) } else if tc.exists { var result flow.OAuth2ConsentRequest require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.Equal(t, challenge, result.ID) require.Equal(t, requestURL, result.RequestURL) require.NotNil(t, result.Client) } }) } } func TestGetLoginRequestWithDuplicateAccept(t *testing.T) { t.Run("Test get login request with duplicate accept", func(t *testing.T) { ctx := context.Background() challenge := "challenge" requestURL := "http://192.0.2.1" conf := internal.NewConfigurationWithDefaults() reg := internal.NewRegistryMemory(t, conf, &contextx.Default{}) cl := &client.Client{LegacyClientID: "client"} require.NoError(t, reg.ClientManager().CreateClient(ctx, cl)) f, err := reg.ConsentManager().CreateLoginRequest(ctx, &flow.LoginRequest{ Client: cl, ID: challenge, RequestURL: requestURL, RequestedAt: time.Now(), }) require.NoError(t, err) challenge, err = f.ToLoginChallenge(ctx, reg) require.NoError(t, err) h := NewHandler(reg, conf) r := x.NewRouterAdmin(conf.AdminURL) h.SetRoutes(r) ts := httptest.NewServer(r) defer ts.Close() c := &http.Client{} sub := "sub123" acceptLogin := &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Ptr(true), Subject: sub} // marshal User to json acceptLoginJson, err := json.Marshal(acceptLogin) if err != nil { panic(err) } // set the HTTP method, url, and request body req, err := http.NewRequest(http.MethodPut, ts.URL+"/admin"+LoginPath+"/accept?challenge="+challenge, bytes.NewBuffer(acceptLoginJson)) if err != nil { panic(err) } resp, err := c.Do(req) require.NoError(t, err) require.EqualValues(t, http.StatusOK, resp.StatusCode) var result flow.OAuth2RedirectTo require.NoError(t, json.NewDecoder(resp.Body).Decode(&result)) require.NotNil(t, result.RedirectTo) require.Contains(t, result.RedirectTo, "login_verifier") req2, err := http.NewRequest(http.MethodPut, ts.URL+"/admin"+LoginPath+"/accept?challenge="+challenge, bytes.NewBuffer(acceptLoginJson)) if err != nil { panic(err) } resp2, err := c.Do(req2) require.NoError(t, err) require.EqualValues(t, http.StatusOK, resp2.StatusCode) var result2 flow.OAuth2RedirectTo require.NoError(t, json.NewDecoder(resp2.Body).Decode(&result2)) require.NotNil(t, result2.RedirectTo) require.Contains(t, result2.RedirectTo, "login_verifier") }) }
Go
hydra/consent/helper.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "net/http" "strings" "time" "github.com/ory/hydra/v2/flow" "github.com/ory/hydra/v2/x" "github.com/ory/x/errorsx" "github.com/gorilla/sessions" "github.com/ory/fosite" "github.com/ory/x/mapx" "github.com/ory/hydra/v2/client" ) func sanitizeClientFromRequest(ar fosite.AuthorizeRequester) *client.Client { return sanitizeClient(ar.GetClient().(*client.Client)) } func sanitizeClient(c *client.Client) *client.Client { cc := new(client.Client) // Remove the hashed secret here *cc = *c cc.Secret = "" return cc } func matchScopes(scopeStrategy fosite.ScopeStrategy, previousConsent []flow.AcceptOAuth2ConsentRequest, requestedScope []string) *flow.AcceptOAuth2ConsentRequest { for _, cs := range previousConsent { var found = true for _, scope := range requestedScope { if !scopeStrategy(cs.GrantedScope, scope) { found = false break } } if found { return &cs } } return nil } func createCsrfSession(w http.ResponseWriter, r *http.Request, conf x.CookieConfigProvider, store sessions.Store, name string, csrfValue string, maxAge time.Duration) error { // Errors can be ignored here, because we always get a session back. Error typically means that the // session doesn't exist yet. session, _ := store.Get(r, name) sameSite := conf.CookieSameSiteMode(r.Context()) if isLegacyCsrfSessionName(name) { sameSite = 0 } session.Values["csrf"] = csrfValue session.Options.HttpOnly = true session.Options.Secure = conf.CookieSecure(r.Context()) session.Options.SameSite = sameSite session.Options.Domain = conf.CookieDomain(r.Context()) session.Options.MaxAge = int(maxAge.Seconds()) if err := session.Save(r, w); err != nil { return errorsx.WithStack(err) } if sameSite == http.SameSiteNoneMode && conf.CookieSameSiteLegacyWorkaround(r.Context()) { return createCsrfSession(w, r, conf, store, legacyCsrfSessionName(name), csrfValue, maxAge) } return nil } func validateCsrfSession(r *http.Request, conf x.CookieConfigProvider, store sessions.Store, name, expectedCSRF string) error { if cookie, err := getCsrfSession(r, store, conf, name); err != nil { return errorsx.WithStack(fosite.ErrRequestForbidden.WithHint("CSRF session cookie could not be decoded.")) } else if csrf, err := mapx.GetString(cookie.Values, "csrf"); err != nil { return errorsx.WithStack(fosite.ErrRequestForbidden.WithHint("No CSRF value available in the session cookie.")) } else if csrf != expectedCSRF { return errorsx.WithStack(fosite.ErrRequestForbidden.WithHint("The CSRF value from the token does not match the CSRF value from the data store.")) } return nil } func getCsrfSession(r *http.Request, store sessions.Store, conf x.CookieConfigProvider, name string) (*sessions.Session, error) { cookie, err := store.Get(r, name) if !isLegacyCsrfSessionName(name) && conf.CookieSameSiteMode(r.Context()) == http.SameSiteNoneMode && conf.CookieSameSiteLegacyWorkaround(r.Context()) && (err != nil || len(cookie.Values) == 0) { return store.Get(r, legacyCsrfSessionName(name)) } return cookie, err } func legacyCsrfSessionName(name string) string { return name + "_legacy" } func isLegacyCsrfSessionName(name string) bool { return strings.HasSuffix(name, "_legacy") }
Go
hydra/consent/helper_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/golang/mock/gomock" "github.com/ory/hydra/v2/flow" "github.com/ory/hydra/v2/internal/mock" "github.com/gorilla/securecookie" "github.com/gorilla/sessions" "github.com/stretchr/testify/assert" "github.com/ory/fosite" "github.com/ory/hydra/v2/client" ) func TestSanitizeClient(t *testing.T) { c := &client.Client{ Secret: "some-secret", } ar := &fosite.AuthorizeRequest{ Request: fosite.Request{ Client: c, }, } got := sanitizeClientFromRequest(ar) assert.Empty(t, got.Secret) assert.NotEmpty(t, c.Secret) } func TestMatchScopes(t *testing.T) { for k, tc := range []struct { granted []flow.AcceptOAuth2ConsentRequest requested []string expectChallenge string }{ { granted: []flow.AcceptOAuth2ConsentRequest{{ID: "1", GrantedScope: []string{"foo", "bar"}}}, requested: []string{"foo", "bar"}, expectChallenge: "1", }, { granted: []flow.AcceptOAuth2ConsentRequest{{ID: "1", GrantedScope: []string{"foo", "bar"}}}, requested: []string{"foo", "bar", "baz"}, expectChallenge: "", }, { granted: []flow.AcceptOAuth2ConsentRequest{ {ID: "1", GrantedScope: []string{"foo", "bar"}}, {ID: "2", GrantedScope: []string{"foo", "bar"}}, }, requested: []string{"foo", "bar"}, expectChallenge: "1", }, { granted: []flow.AcceptOAuth2ConsentRequest{ {ID: "1", GrantedScope: []string{"foo", "bar"}}, {ID: "2", GrantedScope: []string{"foo", "bar", "baz"}}, }, requested: []string{"foo", "bar", "baz"}, expectChallenge: "2", }, { granted: []flow.AcceptOAuth2ConsentRequest{ {ID: "1", GrantedScope: []string{"foo", "bar"}}, {ID: "2", GrantedScope: []string{"foo", "bar", "baz"}}, }, requested: []string{"zab"}, expectChallenge: "", }, } { t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { got := matchScopes(fosite.ExactScopeStrategy, tc.granted, tc.requested) if tc.expectChallenge == "" { assert.Nil(t, got) return } assert.Equal(t, tc.expectChallenge, got.ID) }) } } func TestValidateCsrfSession(t *testing.T) { const name = "oauth2_authentication_csrf" type cookie struct { name string csrfValue string sameSite http.SameSite } for k, tc := range []struct { cookies []cookie csrfValue string sameSiteLegacyWorkaround bool expectError bool sameSite http.SameSite }{ { cookies: []cookie{}, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: false, expectError: true, }, { cookies: []cookie{}, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: true, expectError: true, }, { cookies: []cookie{ { name: name, csrfValue: "WRONG-CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: false, expectError: true, }, { cookies: []cookie{ { name: name, csrfValue: "WRONG-CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: true, expectError: true, }, { cookies: []cookie{ { name: name, csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: false, expectError: false, }, { cookies: []cookie{ { name: name, csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: true, expectError: false, }, { cookies: []cookie{ { name: legacyCsrfSessionName(name), csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: false, expectError: true, }, { cookies: []cookie{ { name: legacyCsrfSessionName(name), csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: true, expectError: false, sameSite: http.SameSiteNoneMode, }, { cookies: []cookie{ { name: legacyCsrfSessionName(name), csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: true, expectError: true, sameSite: http.SameSiteLaxMode, }, { cookies: []cookie{ { name: name, csrfValue: "CSRF-VALUE", sameSite: http.SameSiteNoneMode, }, { name: legacyCsrfSessionName(name), csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: false, expectError: false, }, { cookies: []cookie{ { name: name, csrfValue: "CSRF-VALUE", sameSite: http.SameSiteNoneMode, }, { name: legacyCsrfSessionName(name), csrfValue: "CSRF-VALUE", sameSite: http.SameSiteDefaultMode, }, }, csrfValue: "CSRF-VALUE", sameSiteLegacyWorkaround: true, expectError: false, }, } { t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { ctrl := gomock.NewController(t) t.Cleanup(ctrl.Finish) config := mock.NewMockCookieConfigProvider(ctrl) config.EXPECT().CookieSameSiteLegacyWorkaround(gomock.Any()).Return(tc.sameSiteLegacyWorkaround).AnyTimes() config.EXPECT().IsDevelopmentMode(gomock.Any()).Return(false).AnyTimes() config.EXPECT().CookieSecure(gomock.Any()).Return(false).AnyTimes() sameSite := http.SameSiteDefaultMode if tc.sameSite > 0 { sameSite = tc.sameSite } config.EXPECT().CookieSameSiteMode(gomock.Any()).Return(sameSite).AnyTimes() store := sessions.NewCookieStore(securecookie.GenerateRandomKey(16)) r := httptest.NewRequest(http.MethodGet, "/", nil) w := httptest.NewRecorder() for _, c := range tc.cookies { session, _ := store.Get(r, c.name) session.Values["csrf"] = c.csrfValue session.Options.HttpOnly = true session.Options.Secure = true session.Options.SameSite = c.sameSite err := session.Save(r, w) assert.NoError(t, err, "failed to save cookie %s", c.name) } err := validateCsrfSession(r, config, store, name, tc.csrfValue) if tc.expectError { assert.Error(t, err) } else { assert.NoError(t, err) } }) } } func TestCreateCsrfSession(t *testing.T) { type cookie struct { httpOnly bool secure bool domain string sameSite http.SameSite maxAge int } for _, tc := range []struct { name string secure bool domain string sameSite http.SameSite maxAge time.Duration sameSiteLegacyWorkaround bool expectedCookies map[string]cookie }{ { name: "csrf_default", secure: true, sameSite: http.SameSiteDefaultMode, maxAge: 10 * time.Second, sameSiteLegacyWorkaround: false, expectedCookies: map[string]cookie{ "csrf_default": { httpOnly: true, secure: true, sameSite: 0, // see https://golang.org/doc/go1.16#net/http maxAge: 10, }, }, }, { name: "csrf_lax_insecure", secure: false, sameSite: http.SameSiteLaxMode, maxAge: 20 * time.Second, sameSiteLegacyWorkaround: false, expectedCookies: map[string]cookie{ "csrf_lax_insecure": { httpOnly: true, secure: false, sameSite: http.SameSiteLaxMode, maxAge: 20, }, }, }, { name: "csrf_none", secure: true, sameSite: http.SameSiteNoneMode, maxAge: 30 * time.Second, sameSiteLegacyWorkaround: false, expectedCookies: map[string]cookie{ "csrf_none": { httpOnly: true, secure: true, sameSite: http.SameSiteNoneMode, maxAge: 30, }, }, }, { name: "csrf_none_fallback", secure: true, sameSite: http.SameSiteNoneMode, maxAge: 40 * time.Second, sameSiteLegacyWorkaround: true, expectedCookies: map[string]cookie{ "csrf_none_fallback": { httpOnly: true, secure: true, sameSite: http.SameSiteNoneMode, maxAge: 40, }, "csrf_none_fallback_legacy": { httpOnly: true, secure: true, sameSite: 0, maxAge: 40, }, }, }, { name: "csrf_strict_fallback_ignored", secure: true, sameSite: http.SameSiteStrictMode, maxAge: 50 * time.Second, sameSiteLegacyWorkaround: true, expectedCookies: map[string]cookie{ "csrf_strict_fallback_ignored": { httpOnly: true, secure: true, sameSite: http.SameSiteStrictMode, maxAge: 50, }, }, }, { name: "csrf_domain", secure: true, domain: "foobar.com", sameSite: http.SameSiteNoneMode, expectedCookies: map[string]cookie{ "csrf_domain": { httpOnly: true, secure: true, domain: "foobar.com", sameSite: http.SameSiteNoneMode, }, }, }, } { t.Run(tc.name, func(t *testing.T) { store := sessions.NewCookieStore(securecookie.GenerateRandomKey(16)) rr := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/", nil) ctrl := gomock.NewController(t) t.Cleanup(ctrl.Finish) config := mock.NewMockCookieConfigProvider(ctrl) config.EXPECT().CookieSameSiteMode(gomock.Any()).Return(tc.sameSite).AnyTimes() config.EXPECT().CookieSameSiteLegacyWorkaround(gomock.Any()).Return(tc.sameSiteLegacyWorkaround).AnyTimes() config.EXPECT().CookieSecure(gomock.Any()).Return(tc.secure).AnyTimes() config.EXPECT().CookieDomain(gomock.Any()).Return(tc.domain).AnyTimes() err := createCsrfSession(rr, req, config, store, tc.name, "value", tc.maxAge) assert.NoError(t, err) cookies := make(map[string]cookie) for _, c := range rr.Result().Cookies() { cookies[c.Name] = cookie{ httpOnly: c.HttpOnly, secure: c.Secure, sameSite: c.SameSite, maxAge: c.MaxAge, domain: c.Domain, } } assert.Equal(t, tc.expectedCookies, cookies) }) } }
Go
hydra/consent/janitor_consent_test_helper.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "time" "github.com/ory/hydra/v2/flow" "github.com/ory/x/sqlxx" ) func NewHandledLoginRequest(challenge string, hasError bool, requestedAt time.Time, authenticatedAt sqlxx.NullTime) *flow.HandledLoginRequest { var deniedErr *flow.RequestDeniedError if hasError { deniedErr = &flow.RequestDeniedError{ Name: "consent request denied", Description: "some description", Hint: "some hint", Code: 403, Debug: "some debug", Valid: true, } } return &flow.HandledLoginRequest{ ID: challenge, Error: deniedErr, WasHandled: true, RequestedAt: requestedAt, AuthenticatedAt: authenticatedAt, } } func NewHandledConsentRequest(challenge string, hasError bool, requestedAt time.Time, authenticatedAt sqlxx.NullTime) *flow.AcceptOAuth2ConsentRequest { var deniedErr *flow.RequestDeniedError if hasError { deniedErr = &flow.RequestDeniedError{ Name: "consent request denied", Description: "some description", Hint: "some hint", Code: 403, Debug: "some debug", Valid: true, } } return &flow.AcceptOAuth2ConsentRequest{ ID: challenge, HandledAt: sqlxx.NullTime(time.Now().Round(time.Second)), Error: deniedErr, RequestedAt: requestedAt, AuthenticatedAt: authenticatedAt, WasHandled: true, } }
Go
hydra/consent/manager.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "context" "time" "github.com/gofrs/uuid" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/flow" ) type ForcedObfuscatedLoginSession struct { ClientID string `db:"client_id"` Subject string `db:"subject"` SubjectObfuscated string `db:"subject_obfuscated"` NID uuid.UUID `db:"nid"` } func (ForcedObfuscatedLoginSession) TableName() string { return "hydra_oauth2_obfuscated_authentication_session" } type ( Manager interface { CreateConsentRequest(ctx context.Context, f *flow.Flow, req *flow.OAuth2ConsentRequest) error GetConsentRequest(ctx context.Context, challenge string) (*flow.OAuth2ConsentRequest, error) HandleConsentRequest(ctx context.Context, f *flow.Flow, r *flow.AcceptOAuth2ConsentRequest) (*flow.OAuth2ConsentRequest, error) RevokeSubjectConsentSession(ctx context.Context, user string) error RevokeSubjectClientConsentSession(ctx context.Context, user, client string) error VerifyAndInvalidateConsentRequest(ctx context.Context, f *flow.Flow, verifier string) (*flow.AcceptOAuth2ConsentRequest, error) FindGrantedAndRememberedConsentRequests(ctx context.Context, client, user string) ([]flow.AcceptOAuth2ConsentRequest, error) FindSubjectsGrantedConsentRequests(ctx context.Context, user string, limit, offset int) ([]flow.AcceptOAuth2ConsentRequest, error) FindSubjectsSessionGrantedConsentRequests(ctx context.Context, user, sid string, limit, offset int) ([]flow.AcceptOAuth2ConsentRequest, error) CountSubjectsGrantedConsentRequests(ctx context.Context, user string) (int, error) // Cookie management GetRememberedLoginSession(ctx context.Context, loginSessionFromCookie *flow.LoginSession, id string) (*flow.LoginSession, error) CreateLoginSession(ctx context.Context, session *flow.LoginSession) error DeleteLoginSession(ctx context.Context, id string) (deletedSession *flow.LoginSession, err error) RevokeSubjectLoginSession(ctx context.Context, user string) error ConfirmLoginSession(ctx context.Context, session *flow.LoginSession, id string, authTime time.Time, subject string, remember bool) error CreateLoginRequest(ctx context.Context, req *flow.LoginRequest) (*flow.Flow, error) GetLoginRequest(ctx context.Context, challenge string) (*flow.LoginRequest, error) HandleLoginRequest(ctx context.Context, f *flow.Flow, challenge string, r *flow.HandledLoginRequest) (*flow.LoginRequest, error) VerifyAndInvalidateLoginRequest(ctx context.Context, f *flow.Flow, verifier string) (*flow.HandledLoginRequest, error) CreateForcedObfuscatedLoginSession(ctx context.Context, session *ForcedObfuscatedLoginSession) error GetForcedObfuscatedLoginSession(ctx context.Context, client, obfuscated string) (*ForcedObfuscatedLoginSession, error) ListUserAuthenticatedClientsWithFrontChannelLogout(ctx context.Context, subject, sid string) ([]client.Client, error) ListUserAuthenticatedClientsWithBackChannelLogout(ctx context.Context, subject, sid string) ([]client.Client, error) CreateLogoutRequest(ctx context.Context, request *flow.LogoutRequest) error GetLogoutRequest(ctx context.Context, challenge string) (*flow.LogoutRequest, error) AcceptLogoutRequest(ctx context.Context, challenge string) (*flow.LogoutRequest, error) RejectLogoutRequest(ctx context.Context, challenge string) error VerifyAndInvalidateLogoutRequest(ctx context.Context, verifier string) (*flow.LogoutRequest, error) } ManagerProvider interface { ConsentManager() Manager } )
Go
hydra/consent/manager_test_helpers.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "context" "errors" "fmt" "testing" "time" "github.com/ory/hydra/v2/aead" "github.com/ory/hydra/v2/flow" "github.com/ory/x/assertx" "github.com/ory/x/contextx" gofrsuuid "github.com/gofrs/uuid" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ory/x/sqlxx" "github.com/ory/fosite" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/x" ) func MockConsentRequest(key string, remember bool, rememberFor int, hasError bool, skip bool, authAt bool, loginChallengeBase string, network string) (c *flow.OAuth2ConsentRequest, h *flow.AcceptOAuth2ConsentRequest, f *flow.Flow) { c = &flow.OAuth2ConsentRequest{ ID: makeID("challenge", network, key), RequestedScope: []string{"scopea" + key, "scopeb" + key}, RequestedAudience: []string{"auda" + key, "audb" + key}, Skip: skip, Subject: "subject" + key, OpenIDConnectContext: &flow.OAuth2ConsentRequestOpenIDConnectContext{ ACRValues: []string{"1" + key, "2" + key}, UILocales: []string{"fr" + key, "de" + key}, Display: "popup" + key, }, Client: &client.Client{LegacyClientID: "fk-client-" + key}, RequestURL: "https://request-url/path" + key, LoginChallenge: sqlxx.NullString(makeID(loginChallengeBase, network, key)), LoginSessionID: sqlxx.NullString(makeID("fk-login-session", network, key)), ForceSubjectIdentifier: "forced-subject", Verifier: makeID("verifier", network, key), CSRF: "csrf" + key, ACR: "1", AuthenticatedAt: sqlxx.NullTime(time.Now().UTC().Add(-time.Hour)), RequestedAt: time.Now().UTC(), Context: sqlxx.JSONRawMessage(`{"foo": "bar` + key + `"}`), } f = &flow.Flow{ ID: c.LoginChallenge.String(), LoginVerifier: makeID("login-verifier", network, key), SessionID: c.LoginSessionID, Client: c.Client, State: flow.FlowStateConsentInitialized, ConsentChallengeID: sqlxx.NullString(c.ID), ConsentSkip: c.Skip, ConsentVerifier: sqlxx.NullString(c.Verifier), ConsentCSRF: sqlxx.NullString(c.CSRF), OpenIDConnectContext: c.OpenIDConnectContext, Subject: c.Subject, RequestedScope: c.RequestedScope, RequestedAudience: c.RequestedAudience, RequestURL: c.RequestURL, RequestedAt: c.RequestedAt, } var err *flow.RequestDeniedError if hasError { err = &flow.RequestDeniedError{ Name: "error_name" + key, Description: "error_description" + key, Hint: "error_hint,omitempty" + key, Code: 100, Debug: "error_debug,omitempty" + key, Valid: true, } } var authenticatedAt sqlxx.NullTime if authAt { authenticatedAt = sqlxx.NullTime(time.Now().UTC().Add(-time.Minute)) } h = &flow.AcceptOAuth2ConsentRequest{ ConsentRequest: c, RememberFor: rememberFor, Remember: remember, ID: makeID("challenge", network, key), RequestedAt: time.Now().UTC().Add(-time.Minute), AuthenticatedAt: authenticatedAt, GrantedScope: []string{"scopea" + key, "scopeb" + key}, GrantedAudience: []string{"auda" + key, "audb" + key}, Error: err, HandledAt: sqlxx.NullTime(time.Now().UTC()), // WasUsed: true, } return c, h, f } func MockLogoutRequest(key string, withClient bool, network string) (c *flow.LogoutRequest) { var cl *client.Client if withClient { cl = &client.Client{ LegacyClientID: "fk-client-" + key, } } return &flow.LogoutRequest{ Subject: "subject" + key, ID: makeID("challenge", network, key), Verifier: makeID("verifier", network, key), SessionID: makeID("session", network, key), RPInitiated: true, RequestURL: "http://request-me/", PostLogoutRedirectURI: "http://redirect-me/", WasHandled: false, Accepted: false, Client: cl, } } func MockAuthRequest(key string, authAt bool, network string) (c *flow.LoginRequest, h *flow.HandledLoginRequest, f *flow.Flow) { c = &flow.LoginRequest{ OpenIDConnectContext: &flow.OAuth2ConsentRequestOpenIDConnectContext{ ACRValues: []string{"1" + key, "2" + key}, UILocales: []string{"fr" + key, "de" + key}, Display: "popup" + key, }, RequestedAt: time.Now().UTC().Add(-time.Minute), Client: &client.Client{LegacyClientID: "fk-client-" + key}, Subject: "subject" + key, RequestURL: "https://request-url/path" + key, Skip: true, ID: makeID("challenge", network, key), Verifier: makeID("verifier", network, key), RequestedScope: []string{"scopea" + key, "scopeb" + key}, CSRF: "csrf" + key, SessionID: sqlxx.NullString(makeID("fk-login-session", network, key)), } f = flow.NewFlow(c) var err = &flow.RequestDeniedError{ Name: "error_name" + key, Description: "error_description" + key, Hint: "error_hint,omitempty" + key, Code: 100, Debug: "error_debug,omitempty" + key, Valid: true, } var authenticatedAt time.Time if authAt { authenticatedAt = time.Now().UTC().Add(-time.Minute) } h = &flow.HandledLoginRequest{ LoginRequest: c, RememberFor: 120, Remember: true, ID: makeID("challenge", network, key), RequestedAt: time.Now().UTC().Add(-time.Minute), AuthenticatedAt: sqlxx.NullTime(authenticatedAt), Error: err, Subject: c.Subject, ACR: "acr", ForceSubjectIdentifier: "forced-subject", WasHandled: false, } return c, h, f } func SaneMockHandleConsentRequest(t *testing.T, m Manager, f *flow.Flow, c *flow.OAuth2ConsentRequest, authAt time.Time, rememberFor int, remember bool, hasError bool) *flow.AcceptOAuth2ConsentRequest { var rde *flow.RequestDeniedError if hasError { rde = &flow.RequestDeniedError{ Name: "error_name", Description: "error_description", Hint: "error_hint", Code: 100, Debug: "error_debug", Valid: true, } } h := &flow.AcceptOAuth2ConsentRequest{ ConsentRequest: c, RememberFor: rememberFor, Remember: remember, ID: c.ID, RequestedAt: time.Now().UTC().Add(-time.Minute), AuthenticatedAt: sqlxx.NullTime(authAt), GrantedScope: []string{"scopea", "scopeb"}, GrantedAudience: []string{"auda", "audb"}, Error: rde, WasHandled: false, HandledAt: sqlxx.NullTime(time.Now().UTC().Add(-time.Minute)), } _, err := m.HandleConsentRequest(context.Background(), f, h) require.NoError(t, err) return h } // SaneMockConsentRequest does the same thing as MockConsentRequest but uses less insanity and implicit dependencies. func SaneMockConsentRequest(t *testing.T, m Manager, f *flow.Flow, skip bool) (c *flow.OAuth2ConsentRequest) { c = &flow.OAuth2ConsentRequest{ RequestedScope: []string{"scopea", "scopeb"}, RequestedAudience: []string{"auda", "audb"}, Skip: skip, Subject: f.Subject, OpenIDConnectContext: &flow.OAuth2ConsentRequestOpenIDConnectContext{ ACRValues: []string{"1", "2"}, UILocales: []string{"fr", "de"}, Display: "popup", }, Client: f.Client, RequestURL: "https://request-url/path", LoginChallenge: sqlxx.NullString(f.ID), LoginSessionID: f.SessionID, ForceSubjectIdentifier: "forced-subject", ACR: "1", AuthenticatedAt: sqlxx.NullTime(time.Now().UTC().Add(-time.Hour)), RequestedAt: time.Now().UTC().Add(-time.Hour), Context: sqlxx.JSONRawMessage(`{"foo": "bar"}`), ID: uuid.New().String(), Verifier: uuid.New().String(), CSRF: uuid.New().String(), } require.NoError(t, m.CreateConsentRequest(context.Background(), f, c)) return c } // SaneMockAuthRequest does the same thing as MockAuthRequest but uses less insanity and implicit dependencies. func SaneMockAuthRequest(t *testing.T, m Manager, ls *flow.LoginSession, cl *client.Client) (c *flow.LoginRequest) { c = &flow.LoginRequest{ OpenIDConnectContext: &flow.OAuth2ConsentRequestOpenIDConnectContext{ ACRValues: []string{"1", "2"}, UILocales: []string{"fr", "de"}, Display: "popup", }, RequestedAt: time.Now().UTC().Add(-time.Hour), Client: cl, Subject: ls.Subject, RequestURL: "https://request-url/path", Skip: true, RequestedScope: []string{"scopea", "scopeb"}, SessionID: sqlxx.NullString(ls.ID), CSRF: uuid.New().String(), ID: uuid.New().String(), Verifier: uuid.New().String(), } _, err := m.CreateLoginRequest(context.Background(), c) require.NoError(t, err) return c } func makeID(base string, network string, key string) string { return fmt.Sprintf("%s-%s-%s", base, network, key) } func TestHelperNID(r interface { client.ManagerProvider FlowCipher() *aead.XChaCha20Poly1305 }, t1ValidNID Manager, t2InvalidNID Manager) func(t *testing.T) { testClient := client.Client{LegacyClientID: "2022-03-11-client-nid-test-1"} testLS := flow.LoginSession{ ID: "2022-03-11-ls-nid-test-1", Subject: "2022-03-11-test-1-sub", } testLR := flow.LoginRequest{ ID: "2022-03-11-lr-nid-test-1", Subject: "2022-03-11-test-1-sub", Verifier: "2022-03-11-test-1-ver", RequestedAt: time.Now(), Client: &client.Client{LegacyClientID: "2022-03-11-client-nid-test-1"}, } testHLR := flow.HandledLoginRequest{ LoginRequest: &testLR, RememberFor: 120, Remember: true, ID: testLR.ID, RequestedAt: testLR.RequestedAt, AuthenticatedAt: sqlxx.NullTime(time.Now()), Error: nil, Subject: testLR.Subject, ACR: "acr", ForceSubjectIdentifier: "2022-03-11-test-1-forced-sub", WasHandled: false, } return func(t *testing.T) { ctx := context.Background() require.NoError(t, r.ClientManager().CreateClient(ctx, &testClient)) require.Error(t, t2InvalidNID.CreateLoginSession(ctx, &testLS)) require.NoError(t, t1ValidNID.CreateLoginSession(ctx, &testLS)) _, err := t2InvalidNID.CreateLoginRequest(ctx, &testLR) require.Error(t, err) f, err := t1ValidNID.CreateLoginRequest(ctx, &testLR) require.NoError(t, err) testLR.ID = x.Must(f.ToLoginChallenge(ctx, r)) _, err = t2InvalidNID.GetLoginRequest(ctx, testLR.ID) require.Error(t, err) _, err = t1ValidNID.GetLoginRequest(ctx, testLR.ID) require.NoError(t, err) _, err = t2InvalidNID.HandleLoginRequest(ctx, f, testLR.ID, &testHLR) require.Error(t, err) _, err = t1ValidNID.HandleLoginRequest(ctx, f, testLR.ID, &testHLR) require.NoError(t, err) require.Error(t, t2InvalidNID.ConfirmLoginSession(ctx, &testLS, testLS.ID, time.Now(), testLS.Subject, true)) require.NoError(t, t1ValidNID.ConfirmLoginSession(ctx, &testLS, testLS.ID, time.Now(), testLS.Subject, true)) ls, err := t2InvalidNID.DeleteLoginSession(ctx, testLS.ID) require.Error(t, err) assert.Nil(t, ls) ls, err = t1ValidNID.DeleteLoginSession(ctx, testLS.ID) require.NoError(t, err) assert.Equal(t, testLS.ID, ls.ID) } } type Deps interface { FlowCipher() *aead.XChaCha20Poly1305 contextx.Provider } func ManagerTests(deps Deps, m Manager, clientManager client.Manager, fositeManager x.FositeStorer, network string, parallel bool) func(t *testing.T) { lr := make(map[string]*flow.LoginRequest) return func(t *testing.T) { if parallel { t.Parallel() } ctx := context.Background() t.Run("case=init-fks", func(t *testing.T) { for _, k := range []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "rv1", "rv2"} { require.NoError(t, clientManager.CreateClient(ctx, &client.Client{LegacyClientID: fmt.Sprintf("fk-client-%s", k)})) loginSession := &flow.LoginSession{ ID: makeID("fk-login-session", network, k), AuthenticatedAt: sqlxx.NullTime(time.Now().Round(time.Second).UTC()), Subject: fmt.Sprintf("subject-%s", k), } require.NoError(t, m.CreateLoginSession(ctx, loginSession)) require.NoError(t, m.ConfirmLoginSession(ctx, loginSession, loginSession.ID, time.Now().Round(time.Second).UTC(), loginSession.Subject, true)) lr[k] = &flow.LoginRequest{ ID: makeID("fk-login-challenge", network, k), Subject: fmt.Sprintf("subject%s", k), SessionID: sqlxx.NullString(makeID("fk-login-session", network, k)), Verifier: makeID("fk-login-verifier", network, k), Client: &client.Client{LegacyClientID: fmt.Sprintf("fk-client-%s", k)}, AuthenticatedAt: sqlxx.NullTime(time.Now()), RequestedAt: time.Now(), } _, err := m.CreateLoginRequest(ctx, lr[k]) require.NoError(t, err) } }) t.Run("case=auth-session", func(t *testing.T) { for _, tc := range []struct { s flow.LoginSession }{ { s: flow.LoginSession{ ID: makeID("session", network, "1"), AuthenticatedAt: sqlxx.NullTime(time.Now().Round(time.Second).Add(-time.Minute).UTC()), Subject: "subject1", }, }, { s: flow.LoginSession{ ID: makeID("session", network, "2"), AuthenticatedAt: sqlxx.NullTime(time.Now().Round(time.Minute).Add(-time.Minute).UTC()), Subject: "subject2", }, }, } { t.Run("case=create-get-"+tc.s.ID, func(t *testing.T) { _, err := m.GetRememberedLoginSession(ctx, &tc.s, tc.s.ID) require.EqualError(t, err, x.ErrNotFound.Error(), "%#v", err) err = m.CreateLoginSession(ctx, &tc.s) require.NoError(t, err) _, err = m.GetRememberedLoginSession(ctx, &tc.s, tc.s.ID) require.EqualError(t, err, x.ErrNotFound.Error()) updatedAuth := time.Time(tc.s.AuthenticatedAt).Add(time.Second) require.NoError(t, m.ConfirmLoginSession(ctx, &tc.s, tc.s.ID, updatedAuth, tc.s.Subject, true)) got, err := m.GetRememberedLoginSession(ctx, nil, tc.s.ID) require.NoError(t, err) assert.EqualValues(t, tc.s.ID, got.ID) assert.Equal(t, updatedAuth.Unix(), time.Time(got.AuthenticatedAt).Unix()) // this was updated from confirm... assert.EqualValues(t, tc.s.Subject, got.Subject) time.Sleep(time.Second) // Make sure AuthAt does not equal... updatedAuth2 := time.Now().Truncate(time.Second).UTC() require.NoError(t, m.ConfirmLoginSession(ctx, nil, tc.s.ID, updatedAuth2, "some-other-subject", true)) got2, err := m.GetRememberedLoginSession(ctx, nil, tc.s.ID) require.NoError(t, err) assert.EqualValues(t, tc.s.ID, got2.ID) assert.Equal(t, updatedAuth2.Unix(), time.Time(got2.AuthenticatedAt).Unix()) // this was updated from confirm... assert.EqualValues(t, "some-other-subject", got2.Subject) }) } for _, tc := range []struct { id string }{ { id: makeID("session", network, "1"), }, { id: makeID("session", network, "2"), }, } { t.Run("case=delete-get-"+tc.id, func(t *testing.T) { ls, err := m.DeleteLoginSession(ctx, tc.id) require.NoError(t, err) assert.EqualValues(t, tc.id, ls.ID) _, err = m.GetRememberedLoginSession(ctx, nil, tc.id) require.Error(t, err) }) } }) t.Run("case=auth-request", func(t *testing.T) { for _, tc := range []struct { key string authAt bool }{ {"1", true}, {"2", true}, {"3", true}, {"4", true}, {"5", true}, {"6", false}, {"7", true}, } { t.Run("key="+tc.key, func(t *testing.T) { c, h, f := MockAuthRequest(tc.key, tc.authAt, network) _ = clientManager.CreateClient(ctx, c.Client) // Ignore errors that are caused by duplication loginChallenge := x.Must(f.ToLoginChallenge(ctx, deps)) _, err := m.GetLoginRequest(ctx, loginChallenge) require.Error(t, err) f, err = m.CreateLoginRequest(ctx, c) require.NoError(t, err) loginChallenge = x.Must(f.ToLoginChallenge(ctx, deps)) got1, err := m.GetLoginRequest(ctx, loginChallenge) require.NoError(t, err) assert.False(t, got1.WasHandled) compareAuthenticationRequest(t, c, got1) got1, err = m.HandleLoginRequest(ctx, f, loginChallenge, h) require.NoError(t, err) compareAuthenticationRequest(t, c, got1) loginVerifier := x.Must(f.ToLoginVerifier(ctx, deps)) got2, err := m.VerifyAndInvalidateLoginRequest(ctx, f, loginVerifier) require.NoError(t, err) compareAuthenticationRequest(t, c, got2.LoginRequest) _, err = m.VerifyAndInvalidateLoginRequest(ctx, nil, loginVerifier) require.Error(t, err) loginChallenge = x.Must(f.ToLoginChallenge(ctx, deps)) got1, err = m.GetLoginRequest(ctx, loginChallenge) require.NoError(t, err) assert.True(t, got1.WasHandled) }) } }) t.Run("case=consent-request", func(t *testing.T) { for _, tc := range []struct { key string remember bool rememberFor int hasError bool skip bool authAt bool }{ {"1", true, 0, false, false, true}, {"2", true, 0, true, false, true}, {"3", true, 1, false, false, true}, {"4", false, 0, false, false, true}, {"5", true, 120, false, false, true}, {"6", true, 120, false, true, true}, {"7", false, 0, false, false, false}, } { t.Run("key="+tc.key, func(t *testing.T) { consentRequest, h, f := MockConsentRequest(tc.key, tc.remember, tc.rememberFor, tc.hasError, tc.skip, tc.authAt, "challenge", network) _ = clientManager.CreateClient(ctx, consentRequest.Client) // Ignore errors that are caused by duplication f.NID = deps.Contextualizer().Network(context.Background(), gofrsuuid.Nil) consentChallenge := makeID("challenge", network, tc.key) _, err := m.GetConsentRequest(ctx, consentChallenge) require.Error(t, err) consentChallenge = x.Must(f.ToConsentChallenge(ctx, deps)) consentRequest.ID = consentChallenge err = m.CreateConsentRequest(ctx, f, consentRequest) require.NoError(t, err) got1, err := m.GetConsentRequest(ctx, consentChallenge) require.NoError(t, err) compareConsentRequest(t, consentRequest, got1) assert.False(t, got1.WasHandled) got1, err = m.HandleConsentRequest(ctx, f, h) require.NoError(t, err) assertx.TimeDifferenceLess(t, time.Now(), time.Time(h.HandledAt), 5) compareConsentRequest(t, consentRequest, got1) h.GrantedAudience = sqlxx.StringSliceJSONFormat{"new-audience"} _, err = m.HandleConsentRequest(ctx, f, h) require.NoError(t, err) consentVerifier := x.Must(f.ToConsentVerifier(ctx, deps)) got2, err := m.VerifyAndInvalidateConsentRequest(ctx, f, consentVerifier) require.NoError(t, err) consentRequest.ID = f.ConsentChallengeID.String() compareConsentRequest(t, consentRequest, got2.ConsentRequest) assert.Equal(t, consentRequest.ID, got2.ID) assert.Equal(t, h.GrantedAudience, got2.GrantedAudience) // Trying to update this again should return an error because the consent request was used. h.GrantedAudience = sqlxx.StringSliceJSONFormat{"new-audience", "new-audience-2"} _, err = m.HandleConsentRequest(ctx, f, h) require.Error(t, err) if tc.hasError { assert.True(t, got2.HasError()) } assert.Equal(t, tc.remember, got2.Remember) assert.Equal(t, tc.rememberFor, got2.RememberFor) _, err = m.VerifyAndInvalidateConsentRequest(ctx, f, makeID("verifier", network, tc.key)) require.Error(t, err) // Because we don't persist the flow any more, we can't check for this. //got1, err = m.GetConsentRequest(ctx, consentChallenge) //require.NoError(t, err) //assert.True(t, got1.WasHandled) }) } for _, tc := range []struct { keyC string keyS string expectedLength int }{ {"1", "1", 1}, {"2", "2", 0}, // {"3", "3", 0}, // Some consent is given in some other test case. Yay global fixtues :) {"4", "4", 0}, {"1", "2", 0}, {"2", "1", 0}, {"5", "5", 1}, {"6", "6", 0}, } { t.Run("key="+tc.keyC+"-"+tc.keyS, func(t *testing.T) { rs, err := m.FindGrantedAndRememberedConsentRequests(ctx, "fk-client-"+tc.keyC, "subject"+tc.keyS) if tc.expectedLength == 0 { assert.Nil(t, rs) assert.EqualError(t, err, ErrNoPreviousConsentFound.Error()) } else { require.NoError(t, err) assert.Len(t, rs, tc.expectedLength) } }) } }) t.Run("case=revoke-auth-request", func(t *testing.T) { require.NoError(t, m.CreateLoginSession(ctx, &flow.LoginSession{ ID: makeID("rev-session", network, "-1"), AuthenticatedAt: sqlxx.NullTime(time.Now()), Subject: "subject-1", })) require.NoError(t, m.CreateLoginSession(ctx, &flow.LoginSession{ ID: makeID("rev-session", network, "-2"), AuthenticatedAt: sqlxx.NullTime(time.Now()), Subject: "subject-2", })) require.NoError(t, m.CreateLoginSession(ctx, &flow.LoginSession{ ID: makeID("rev-session", network, "-3"), AuthenticatedAt: sqlxx.NullTime(time.Now()), Subject: "subject-1", })) for i, tc := range []struct { subject string ids []string }{ { subject: "subject-1", ids: []string{makeID("rev-session", network, "-1"), makeID("rev-session", network, "-3")}, }, { subject: "subject-2", ids: []string{makeID("rev-session", network, "-1"), makeID("rev-session", network, "-3"), makeID("rev-session", network, "-2")}, }, } { t.Run(fmt.Sprintf("case=%d/subject=%s", i, tc.subject), func(t *testing.T) { require.NoError(t, m.RevokeSubjectLoginSession(ctx, tc.subject)) for _, id := range tc.ids { t.Run(fmt.Sprintf("id=%s", id), func(t *testing.T) { _, err := m.GetRememberedLoginSession(ctx, nil, id) assert.EqualError(t, err, x.ErrNotFound.Error()) }) } }) } }) challengerv1 := makeID("challenge", network, "rv1") challengerv2 := makeID("challenge", network, "rv2") t.Run("case=revoke-used-consent-request", func(t *testing.T) { cr1, hcr1, f1 := MockConsentRequest("rv1", false, 0, false, false, false, "fk-login-challenge", network) cr2, hcr2, f2 := MockConsentRequest("rv2", false, 0, false, false, false, "fk-login-challenge", network) f1.NID = deps.Contextualizer().Network(context.Background(), gofrsuuid.Nil) f2.NID = deps.Contextualizer().Network(context.Background(), gofrsuuid.Nil) // Ignore duplication errors _ = clientManager.CreateClient(ctx, cr1.Client) _ = clientManager.CreateClient(ctx, cr2.Client) err := m.CreateConsentRequest(ctx, f1, cr1) require.NoError(t, err) err = m.CreateConsentRequest(ctx, f2, cr2) require.NoError(t, err) _, err = m.HandleConsentRequest(ctx, f1, hcr1) require.NoError(t, err) _, err = m.HandleConsentRequest(ctx, f2, hcr2) require.NoError(t, err) _, err = m.VerifyAndInvalidateConsentRequest(ctx, f1, x.Must(f1.ToConsentVerifier(ctx, deps))) require.NoError(t, err) _, err = m.VerifyAndInvalidateConsentRequest(ctx, f2, x.Must(f2.ToConsentVerifier(ctx, deps))) require.NoError(t, err) require.NoError(t, fositeManager.CreateAccessTokenSession( ctx, makeID("", network, "trva1"), &fosite.Request{Client: cr1.Client, ID: f1.ConsentChallengeID.String(), RequestedAt: time.Now()}, )) require.NoError(t, fositeManager.CreateRefreshTokenSession( ctx, makeID("", network, "rrva1"), &fosite.Request{Client: cr1.Client, ID: f1.ConsentChallengeID.String(), RequestedAt: time.Now()}, )) require.NoError(t, fositeManager.CreateAccessTokenSession( ctx, makeID("", network, "trva2"), &fosite.Request{Client: cr2.Client, ID: f2.ConsentChallengeID.String(), RequestedAt: time.Now()}, )) require.NoError(t, fositeManager.CreateRefreshTokenSession( ctx, makeID("", network, "rrva2"), &fosite.Request{Client: cr2.Client, ID: f2.ConsentChallengeID.String(), RequestedAt: time.Now()}, )) for i, tc := range []struct { subject string client string at string rt string ids []string }{ { at: makeID("", network, "trva1"), rt: makeID("", network, "rrva1"), subject: "subjectrv1", client: "", ids: []string{challengerv1}, }, { at: makeID("", network, "trva2"), rt: makeID("", network, "rrva2"), subject: "subjectrv2", client: "fk-client-rv2", ids: []string{challengerv2}, }, } { t.Run(fmt.Sprintf("case=%d/subject=%s", i, tc.subject), func(t *testing.T) { _, err := fositeManager.GetAccessTokenSession(ctx, tc.at, nil) assert.NoError(t, err) _, err = fositeManager.GetRefreshTokenSession(ctx, tc.rt, nil) assert.NoError(t, err) if tc.client == "" { require.NoError(t, m.RevokeSubjectConsentSession(ctx, tc.subject)) } else { require.NoError(t, m.RevokeSubjectClientConsentSession(ctx, tc.subject, tc.client)) } for _, id := range tc.ids { t.Run(fmt.Sprintf("id=%s", id), func(t *testing.T) { _, err := m.GetConsentRequest(ctx, id) assert.True(t, errors.Is(err, x.ErrNotFound)) }) } r, err := fositeManager.GetAccessTokenSession(ctx, tc.at, nil) assert.Error(t, err, "%+v", r) r, err = fositeManager.GetRefreshTokenSession(ctx, tc.rt, nil) assert.Error(t, err, "%+v", r) }) } require.EqualError(t, m.RevokeSubjectConsentSession(ctx, "i-do-not-exist"), x.ErrNotFound.Error()) require.EqualError(t, m.RevokeSubjectClientConsentSession(ctx, "i-do-not-exist", "i-do-not-exist"), x.ErrNotFound.Error()) }) t.Run("case=list-used-consent-requests", func(t *testing.T) { f1, err := m.CreateLoginRequest(ctx, lr["rv1"]) require.NoError(t, err) f2, err := m.CreateLoginRequest(ctx, lr["rv2"]) require.NoError(t, err) cr1, hcr1, _ := MockConsentRequest("rv1", true, 0, false, false, false, "fk-login-challenge", network) cr2, hcr2, _ := MockConsentRequest("rv2", false, 0, false, false, false, "fk-login-challenge", network) // Ignore duplicate errors _ = clientManager.CreateClient(ctx, cr1.Client) _ = clientManager.CreateClient(ctx, cr2.Client) err = m.CreateConsentRequest(ctx, f1, cr1) require.NoError(t, err) err = m.CreateConsentRequest(ctx, f2, cr2) require.NoError(t, err) _, err = m.HandleConsentRequest(ctx, f1, hcr1) require.NoError(t, err) _, err = m.HandleConsentRequest(ctx, f2, hcr2) require.NoError(t, err) handledConsentRequest1, err := m.VerifyAndInvalidateConsentRequest(ctx, f1, x.Must(f1.ToConsentVerifier(ctx, deps))) require.NoError(t, err) handledConsentRequest2, err := m.VerifyAndInvalidateConsentRequest(ctx, f2, x.Must(f2.ToConsentVerifier(ctx, deps))) require.NoError(t, err) for i, tc := range []struct { subject string sid string challenges []string clients []string }{ { subject: cr1.Subject, sid: makeID("fk-login-session", network, "rv1"), challenges: []string{handledConsentRequest1.ID}, clients: []string{"fk-client-rv1"}, }, { subject: cr2.Subject, sid: makeID("fk-login-session", network, "rv2"), challenges: []string{handledConsentRequest2.ID}, clients: []string{"fk-client-rv2"}, }, { subject: "subjectrv3", sid: makeID("fk-login-session", network, "rv2"), challenges: []string{}, clients: []string{}, }, } { t.Run(fmt.Sprintf("case=%d/subject=%s/session=%s", i, tc.subject, tc.sid), func(t *testing.T) { consents, err := m.FindSubjectsSessionGrantedConsentRequests(ctx, tc.subject, tc.sid, 100, 0) assert.Equal(t, len(tc.challenges), len(consents)) if len(tc.challenges) == 0 { assert.EqualError(t, err, ErrNoPreviousConsentFound.Error()) } else { require.NoError(t, err) for _, consent := range consents { assert.Contains(t, tc.challenges, consent.ID) assert.Contains(t, tc.clients, consent.ConsentRequest.Client.GetID()) } } n, err := m.CountSubjectsGrantedConsentRequests(ctx, tc.subject) require.NoError(t, err) assert.Equal(t, n, len(tc.challenges)) }) } for i, tc := range []struct { subject string challenges []string clients []string }{ { subject: "subjectrv1", challenges: []string{handledConsentRequest1.ID}, clients: []string{"fk-client-rv1"}, }, { subject: "subjectrv2", challenges: []string{handledConsentRequest2.ID}, clients: []string{"fk-client-rv2"}, }, { subject: "subjectrv3", challenges: []string{}, clients: []string{}, }, } { t.Run(fmt.Sprintf("case=%d/subject=%s", i, tc.subject), func(t *testing.T) { consents, err := m.FindSubjectsGrantedConsentRequests(ctx, tc.subject, 100, 0) assert.Equal(t, len(tc.challenges), len(consents)) if len(tc.challenges) == 0 { assert.EqualError(t, err, ErrNoPreviousConsentFound.Error()) } else { require.NoError(t, err) for _, consent := range consents { assert.Contains(t, tc.challenges, consent.ID) assert.Contains(t, tc.clients, consent.ConsentRequest.Client.GetID()) } } n, err := m.CountSubjectsGrantedConsentRequests(ctx, tc.subject) require.NoError(t, err) assert.Equal(t, n, len(tc.challenges)) }) } t.Run("case=obfuscated", func(t *testing.T) { _, err := m.GetForcedObfuscatedLoginSession(ctx, "fk-client-1", "obfuscated-1") require.True(t, errors.Is(err, x.ErrNotFound)) expect := &ForcedObfuscatedLoginSession{ ClientID: "fk-client-1", Subject: "subject-1", SubjectObfuscated: "obfuscated-1", } require.NoError(t, m.CreateForcedObfuscatedLoginSession(ctx, expect)) got, err := m.GetForcedObfuscatedLoginSession(ctx, "fk-client-1", "obfuscated-1") require.NoError(t, err) require.NotEqual(t, got.NID, gofrsuuid.Nil) got.NID = gofrsuuid.Nil assert.EqualValues(t, expect, got) expect = &ForcedObfuscatedLoginSession{ ClientID: "fk-client-1", Subject: "subject-1", SubjectObfuscated: "obfuscated-2", } require.NoError(t, m.CreateForcedObfuscatedLoginSession(ctx, expect)) got, err = m.GetForcedObfuscatedLoginSession(ctx, "fk-client-1", "obfuscated-2") require.NotEqual(t, got.NID, gofrsuuid.Nil) got.NID = gofrsuuid.Nil require.NoError(t, err) assert.EqualValues(t, expect, got) _, err = m.GetForcedObfuscatedLoginSession(ctx, "fk-client-1", "obfuscated-1") require.True(t, errors.Is(err, x.ErrNotFound)) }) t.Run("case=ListUserAuthenticatedClientsWithFrontAndBackChannelLogout", func(t *testing.T) { // The idea of this test is to create two identities (subjects) with 4 sessions each, where // only some sessions have been associated with a client that has a front channel logout url subjects := make([]string, 1) for k := range subjects { subjects[k] = fmt.Sprintf("subject-ListUserAuthenticatedClientsWithFrontAndBackChannelLogout-%d", k) } sessions := make([]flow.LoginSession, len(subjects)*1) frontChannels := map[string][]client.Client{} backChannels := map[string][]client.Client{} for k := range sessions { id := uuid.New().String() subject := subjects[k%len(subjects)] t.Run(fmt.Sprintf("create/session=%s/subject=%s", id, subject), func(t *testing.T) { ls := &flow.LoginSession{ ID: id, AuthenticatedAt: sqlxx.NullTime(time.Now()), Subject: subject, } require.NoError(t, m.CreateLoginSession(ctx, ls)) require.NoError(t, m.ConfirmLoginSession(ctx, ls, ls.ID, time.Now(), ls.Subject, true)) cl := &client.Client{LegacyClientID: uuid.New().String()} switch k % 4 { case 0: cl.FrontChannelLogoutURI = "http://some-url.com/" frontChannels[id] = append(frontChannels[id], *cl) case 1: cl.BackChannelLogoutURI = "http://some-url.com/" backChannels[id] = append(backChannels[id], *cl) case 2: cl.FrontChannelLogoutURI = "http://some-url.com/" cl.BackChannelLogoutURI = "http://some-url.com/" frontChannels[id] = append(frontChannels[id], *cl) backChannels[id] = append(backChannels[id], *cl) } require.NoError(t, clientManager.CreateClient(ctx, cl)) ar := SaneMockAuthRequest(t, m, ls, cl) f := flow.NewFlow(ar) f.NID = deps.Contextualizer().Network(ctx, gofrsuuid.Nil) cr := SaneMockConsentRequest(t, m, f, false) _ = SaneMockHandleConsentRequest(t, m, f, cr, time.Time{}, 0, false, false) _, err = m.VerifyAndInvalidateConsentRequest(ctx, f, x.Must(f.ToConsentVerifier(ctx, deps))) require.NoError(t, err) sessions[k] = *ls }) } for _, ls := range sessions { check := func(t *testing.T, expected map[string][]client.Client, actual []client.Client) { es, ok := expected[ls.ID] if !ok { require.Len(t, actual, 0) return } require.Len(t, actual, len(es)) for _, e := range es { var found bool for _, a := range actual { if e.GetID() == a.GetID() { found = true } assert.Equal(t, e.GetID(), a.GetID()) assert.Equal(t, e.FrontChannelLogoutURI, a.FrontChannelLogoutURI) assert.Equal(t, e.BackChannelLogoutURI, a.BackChannelLogoutURI) } require.True(t, found) } } t.Run(fmt.Sprintf("method=ListUserAuthenticatedClientsWithFrontChannelLogout/session=%s/subject=%s", ls.ID, ls.Subject), func(t *testing.T) { actual, err := m.ListUserAuthenticatedClientsWithFrontChannelLogout(ctx, ls.Subject, ls.ID) require.NoError(t, err) check(t, frontChannels, actual) }) t.Run(fmt.Sprintf("method=ListUserAuthenticatedClientsWithBackChannelLogout/session=%s", ls.ID), func(t *testing.T) { actual, err := m.ListUserAuthenticatedClientsWithBackChannelLogout(ctx, ls.Subject, ls.ID) require.NoError(t, err) check(t, backChannels, actual) }) } }) t.Run("case=LogoutRequest", func(t *testing.T) { for k, tc := range []struct { key string authAt bool withClient bool }{ {"LogoutRequest-1", true, true}, {"LogoutRequest-2", true, true}, {"LogoutRequest-3", true, true}, {"LogoutRequest-4", true, true}, {"LogoutRequest-5", true, false}, {"LogoutRequest-6", false, false}, } { t.Run("key="+tc.key, func(t *testing.T) { challenge := makeID("challenge", network, tc.key) verifier := makeID("verifier", network, tc.key) c := MockLogoutRequest(tc.key, tc.withClient, network) if tc.withClient { require.NoError(t, clientManager.CreateClient(ctx, c.Client)) // Ignore errors that are caused by duplication } _, err := m.GetLogoutRequest(ctx, challenge) require.Error(t, err) require.NoError(t, m.CreateLogoutRequest(ctx, c)) got2, err := m.GetLogoutRequest(ctx, challenge) require.NoError(t, err) assert.False(t, got2.WasHandled) assert.False(t, got2.Accepted) compareLogoutRequest(t, c, got2) if k%2 == 0 { got2, err = m.AcceptLogoutRequest(ctx, challenge) require.NoError(t, err) assert.True(t, got2.Accepted) compareLogoutRequest(t, c, got2) got3, err := m.VerifyAndInvalidateLogoutRequest(ctx, verifier) require.NoError(t, err) assert.True(t, got3.Accepted) assert.True(t, got3.WasHandled) compareLogoutRequest(t, c, got3) _, err = m.VerifyAndInvalidateLogoutRequest(ctx, verifier) require.Error(t, err) got2, err = m.GetLogoutRequest(ctx, challenge) require.NoError(t, err) compareLogoutRequest(t, got3, got2) assert.True(t, got2.WasHandled) } else { require.NoError(t, m.RejectLogoutRequest(ctx, challenge)) _, err = m.GetLogoutRequest(ctx, challenge) require.Error(t, err) } }) } }) }) t.Run("case=foreign key regression", func(t *testing.T) { cl := &client.Client{LegacyClientID: uuid.New().String()} require.NoError(t, clientManager.CreateClient(ctx, cl)) subject := uuid.New().String() s := flow.LoginSession{ ID: uuid.New().String(), AuthenticatedAt: sqlxx.NullTime(time.Now().Round(time.Minute).Add(-time.Minute).UTC()), Subject: subject, } require.NoError(t, m.CreateLoginSession(ctx, &s)) require.NoError(t, m.ConfirmLoginSession(ctx, &s, s.ID, time.Time(s.AuthenticatedAt), s.Subject, false)) lr := &flow.LoginRequest{ ID: uuid.New().String(), Subject: uuid.New().String(), Verifier: uuid.New().String(), Client: cl, AuthenticatedAt: sqlxx.NullTime(time.Now()), RequestedAt: time.Now(), SessionID: sqlxx.NullString(s.ID), } f, err := m.CreateLoginRequest(ctx, lr) require.NoError(t, err) expected := &flow.OAuth2ConsentRequest{ ID: x.Must(f.ToConsentChallenge(ctx, deps)), Skip: true, Subject: subject, OpenIDConnectContext: nil, Client: cl, ClientID: cl.LegacyClientID, RequestURL: "", LoginChallenge: sqlxx.NullString(lr.ID), LoginSessionID: sqlxx.NullString(s.ID), Verifier: uuid.New().String(), CSRF: uuid.New().String(), } err = m.CreateConsentRequest(ctx, f, expected) require.NoError(t, err) result, err := m.GetConsentRequest(ctx, expected.ID) require.NoError(t, err) assert.EqualValues(t, expected.ID, result.ID) _, err = m.DeleteLoginSession(ctx, s.ID) require.NoError(t, err) result, err = m.GetConsentRequest(ctx, expected.ID) require.NoError(t, err) assert.EqualValues(t, expected.ID, result.ID) }) } } func compareLogoutRequest(t *testing.T, a, b *flow.LogoutRequest) { require.True(t, (a.Client != nil && b.Client != nil) || (a.Client == nil && b.Client == nil)) if a.Client != nil { assert.EqualValues(t, a.Client.GetID(), b.Client.GetID()) } assert.EqualValues(t, a.ID, b.ID) assert.EqualValues(t, a.Subject, b.Subject) assert.EqualValues(t, a.Verifier, b.Verifier) assert.EqualValues(t, a.RequestURL, b.RequestURL) assert.EqualValues(t, a.PostLogoutRedirectURI, b.PostLogoutRedirectURI) assert.EqualValues(t, a.RPInitiated, b.RPInitiated) assert.EqualValues(t, a.SessionID, b.SessionID) } func compareAuthenticationRequest(t *testing.T, a, b *flow.LoginRequest) { assert.EqualValues(t, a.Client.GetID(), b.Client.GetID()) assert.EqualValues(t, *a.OpenIDConnectContext, *b.OpenIDConnectContext) assert.EqualValues(t, a.Subject, b.Subject) assert.EqualValues(t, a.RequestedScope, b.RequestedScope) assert.EqualValues(t, a.Verifier, b.Verifier) assert.EqualValues(t, a.RequestURL, b.RequestURL) assert.EqualValues(t, a.CSRF, b.CSRF) assert.EqualValues(t, a.Skip, b.Skip) assert.EqualValues(t, a.SessionID, b.SessionID) } func compareConsentRequest(t *testing.T, a, b *flow.OAuth2ConsentRequest) { assert.EqualValues(t, a.Client.GetID(), b.Client.GetID()) assert.EqualValues(t, a.ID, b.ID) assert.EqualValues(t, *a.OpenIDConnectContext, *b.OpenIDConnectContext) assert.EqualValues(t, a.Subject, b.Subject) assert.EqualValues(t, a.RequestedScope, b.RequestedScope) assert.EqualValues(t, a.Verifier, b.Verifier) assert.EqualValues(t, a.RequestURL, b.RequestURL) assert.EqualValues(t, a.CSRF, b.CSRF) assert.EqualValues(t, a.Skip, b.Skip) assert.EqualValues(t, a.LoginChallenge, b.LoginChallenge) assert.EqualValues(t, a.LoginSessionID, b.LoginSessionID) }
Go
hydra/consent/registry.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "context" "github.com/ory/fosite/handler/openid" "github.com/ory/hydra/v2/aead" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/internal/kratos" "github.com/ory/hydra/v2/x" ) type InternalRegistry interface { x.RegistryWriter x.RegistryCookieStore x.RegistryLogger x.HTTPClientProvider kratos.Provider Registry client.Registry FlowCipher() *aead.XChaCha20Poly1305 OAuth2Storage() x.FositeStorer OpenIDConnectRequestValidator() *openid.OpenIDConnectRequestValidator } type Registry interface { ConsentManager() Manager ConsentStrategy() Strategy SubjectIdentifierAlgorithm(ctx context.Context) map[string]SubjectIdentifierAlgorithm }
Go
hydra/consent/sdk_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent_test import ( "context" "fmt" "net/http" "net/http/httptest" "testing" "time" hydra "github.com/ory/hydra-client-go/v2" . "github.com/ory/hydra/v2/flow" "github.com/ory/x/httprouterx" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" . "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/internal" "github.com/ory/hydra/v2/x" "github.com/ory/x/contextx" ) func makeID(base string, network string, key string) string { return fmt.Sprintf("%s-%s-%s", base, network, key) } func TestSDK(t *testing.T) { ctx := context.Background() network := "t1" conf := internal.NewConfigurationWithDefaults() conf.MustSet(ctx, config.KeyIssuerURL, "https://www.ory.sh") conf.MustSet(ctx, config.KeyAccessTokenLifespan, time.Minute) reg := internal.NewRegistryMemory(t, conf, &contextx.Default{}) consentChallenge := func(f *Flow) string { return x.Must(f.ToConsentChallenge(ctx, reg)) } consentVerifier := func(f *Flow) string { return x.Must(f.ToConsentVerifier(ctx, reg)) } loginChallenge := func(f *Flow) string { return x.Must(f.ToLoginChallenge(ctx, reg)) } router := x.NewRouterPublic() h := NewHandler(reg, conf) h.SetRoutes(httprouterx.NewRouterAdminWithPrefixAndRouter(router.Router, "/admin", conf.AdminURL)) ts := httptest.NewServer(router) sdk := hydra.NewAPIClient(hydra.NewConfiguration()) sdk.GetConfig().Servers = hydra.ServerConfigurations{{URL: ts.URL}} m := reg.ConsentManager() require.NoError(t, m.CreateLoginSession(context.Background(), &LoginSession{ ID: "session1", Subject: "subject1", })) ar1, _, _ := MockAuthRequest("1", false, network) ar2, _, _ := MockAuthRequest("2", false, network) require.NoError(t, m.CreateLoginSession(context.Background(), &LoginSession{ ID: ar1.SessionID.String(), Subject: ar1.Subject, })) require.NoError(t, m.CreateLoginSession(context.Background(), &LoginSession{ ID: ar2.SessionID.String(), Subject: ar2.Subject, })) _, err := m.CreateLoginRequest(context.Background(), ar1) require.NoError(t, err) _, err = m.CreateLoginRequest(context.Background(), ar2) require.NoError(t, err) cr1, hcr1, _ := MockConsentRequest("1", false, 0, false, false, false, "fk-login-challenge", network) cr2, hcr2, _ := MockConsentRequest("2", false, 0, false, false, false, "fk-login-challenge", network) cr3, hcr3, _ := MockConsentRequest("3", true, 3600, false, false, false, "fk-login-challenge", network) cr4, hcr4, _ := MockConsentRequest("4", true, 3600, false, false, false, "fk-login-challenge", network) require.NoError(t, reg.ClientManager().CreateClient(context.Background(), cr1.Client)) require.NoError(t, reg.ClientManager().CreateClient(context.Background(), cr2.Client)) require.NoError(t, reg.ClientManager().CreateClient(context.Background(), cr3.Client)) require.NoError(t, reg.ClientManager().CreateClient(context.Background(), cr4.Client)) cr1Flow, err := m.CreateLoginRequest(context.Background(), &LoginRequest{ ID: cr1.LoginChallenge.String(), Subject: cr1.Subject, Client: cr1.Client, Verifier: cr1.ID, RequestedAt: time.Now(), }) require.NoError(t, err) cr1Flow.LoginSkip = ar1.Skip cr2Flow, err := m.CreateLoginRequest(context.Background(), &LoginRequest{ ID: cr2.LoginChallenge.String(), Subject: cr2.Subject, Client: cr2.Client, Verifier: cr2.ID, RequestedAt: time.Now(), }) require.NoError(t, err) cr2Flow.LoginSkip = ar2.Skip loginSession3 := &LoginSession{ID: cr3.LoginSessionID.String()} require.NoError(t, m.CreateLoginSession(context.Background(), loginSession3)) require.NoError(t, m.ConfirmLoginSession(context.Background(), loginSession3, loginSession3.ID, time.Now(), cr3.Subject, true)) cr3Flow, err := m.CreateLoginRequest(context.Background(), &LoginRequest{ ID: cr3.LoginChallenge.String(), Subject: cr3.Subject, Client: cr3.Client, Verifier: cr3.ID, RequestedAt: hcr3.RequestedAt, SessionID: cr3.LoginSessionID, }) require.NoError(t, err) loginSession4 := &LoginSession{ID: cr4.LoginSessionID.String()} require.NoError(t, m.CreateLoginSession(context.Background(), loginSession4)) require.NoError(t, m.ConfirmLoginSession(context.Background(), loginSession4, loginSession4.ID, time.Now(), cr4.Subject, true)) cr4Flow, err := m.CreateLoginRequest(context.Background(), &LoginRequest{ ID: cr4.LoginChallenge.String(), Client: cr4.Client, Verifier: cr4.ID, SessionID: cr4.LoginSessionID, }) require.NoError(t, err) require.NoError(t, m.CreateConsentRequest(context.Background(), cr1Flow, cr1)) require.NoError(t, m.CreateConsentRequest(context.Background(), cr2Flow, cr2)) require.NoError(t, m.CreateConsentRequest(context.Background(), cr3Flow, cr3)) require.NoError(t, m.CreateConsentRequest(context.Background(), cr4Flow, cr4)) _, err = m.HandleConsentRequest(context.Background(), cr1Flow, hcr1) require.NoError(t, err) _, err = m.HandleConsentRequest(context.Background(), cr2Flow, hcr2) require.NoError(t, err) _, err = m.HandleConsentRequest(context.Background(), cr3Flow, hcr3) require.NoError(t, err) _, err = m.HandleConsentRequest(context.Background(), cr4Flow, hcr4) require.NoError(t, err) _, err = m.VerifyAndInvalidateConsentRequest(context.Background(), cr3Flow, consentVerifier(cr3Flow)) require.NoError(t, err) _, err = m.VerifyAndInvalidateConsentRequest(context.Background(), cr4Flow, consentVerifier(cr4Flow)) require.NoError(t, err) lur1 := MockLogoutRequest("testsdk-1", true, network) require.NoError(t, reg.ClientManager().CreateClient(context.Background(), lur1.Client)) require.NoError(t, m.CreateLogoutRequest(context.Background(), lur1)) lur2 := MockLogoutRequest("testsdk-2", false, network) require.NoError(t, m.CreateLogoutRequest(context.Background(), lur2)) cr1.ID = consentChallenge(cr1Flow) crGot := execute[hydra.OAuth2ConsentRequest](t, sdk.OAuth2Api.GetOAuth2ConsentRequest(ctx).ConsentChallenge(cr1.ID)) compareSDKConsentRequest(t, cr1, *crGot) cr2.ID = consentChallenge(cr2Flow) crGot = execute[hydra.OAuth2ConsentRequest](t, sdk.OAuth2Api.GetOAuth2ConsentRequest(ctx).ConsentChallenge(cr2.ID)) compareSDKConsentRequest(t, cr2, *crGot) ar1.ID = loginChallenge(cr1Flow) arGot := execute[hydra.OAuth2LoginRequest](t, sdk.OAuth2Api.GetOAuth2LoginRequest(ctx).LoginChallenge(ar1.ID)) compareSDKLoginRequest(t, ar1, *arGot) ar2.ID = loginChallenge(cr2Flow) arGot = execute[hydra.OAuth2LoginRequest](t, sdk.OAuth2Api.GetOAuth2LoginRequest(ctx).LoginChallenge(ar2.ID)) require.NoError(t, err) compareSDKLoginRequest(t, ar2, *arGot) _, err = sdk.OAuth2Api.RevokeOAuth2LoginSessions(ctx).Subject("subject1").Execute() require.NoError(t, err) _, err = sdk.OAuth2Api.RevokeOAuth2ConsentSessions(ctx).Subject("subject1").Execute() require.Error(t, err) _, err = sdk.OAuth2Api.RevokeOAuth2ConsentSessions(ctx).Subject(cr4.Subject).Client(cr4.Client.GetID()).Execute() require.NoError(t, err) _, err = sdk.OAuth2Api.RevokeOAuth2ConsentSessions(ctx).Subject("subject1").All(true).Execute() require.NoError(t, err) _, _, err = sdk.OAuth2Api.GetOAuth2ConsentRequest(ctx).ConsentChallenge(makeID("challenge", network, "1")).Execute() require.Error(t, err) cr2.ID = consentChallenge(cr2Flow) crGot, _, err = sdk.OAuth2Api.GetOAuth2ConsentRequest(ctx).ConsentChallenge(cr2.ID).Execute() require.NoError(t, err) compareSDKConsentRequest(t, cr2, *crGot) _, err = sdk.OAuth2Api.RevokeOAuth2ConsentSessions(ctx).Subject("subject2").Client("fk-client-2").Execute() require.NoError(t, err) _, _, err = sdk.OAuth2Api.GetOAuth2ConsentRequest(ctx).ConsentChallenge(makeID("challenge", network, "2")).Execute() require.Error(t, err) csGot, _, err := sdk.OAuth2Api.ListOAuth2ConsentSessions(ctx).Subject("subject3").Execute() require.NoError(t, err) assert.Equal(t, 1, len(csGot)) csGot, _, err = sdk.OAuth2Api.ListOAuth2ConsentSessions(ctx).Subject("subject2").Execute() require.NoError(t, err) assert.Equal(t, 0, len(csGot)) csGot, _, err = sdk.OAuth2Api.ListOAuth2ConsentSessions(ctx).Subject("subject3").LoginSessionId("fk-login-session-t1-3").Execute() require.NoError(t, err) assert.Equal(t, 1, len(csGot)) csGot, _, err = sdk.OAuth2Api.ListOAuth2ConsentSessions(ctx).Subject("subject3").LoginSessionId("fk-login-session-t1-X").Execute() require.NoError(t, err) assert.Equal(t, 0, len(csGot)) luGot, _, err := sdk.OAuth2Api.GetOAuth2LogoutRequest(ctx).LogoutChallenge(makeID("challenge", network, "testsdk-1")).Execute() require.NoError(t, err) compareSDKLogoutRequest(t, lur1, luGot) luaGot, _, err := sdk.OAuth2Api.AcceptOAuth2LogoutRequest(ctx).LogoutChallenge(makeID("challenge", network, "testsdk-1")).Execute() require.NoError(t, err) assert.EqualValues(t, "https://www.ory.sh/oauth2/sessions/logout?logout_verifier="+makeID("verifier", network, "testsdk-1"), luaGot.RedirectTo) _, err = sdk.OAuth2Api.RejectOAuth2LogoutRequest(ctx).LogoutChallenge(lur2.ID).Execute() require.NoError(t, err) _, _, err = sdk.OAuth2Api.GetOAuth2LogoutRequest(ctx).LogoutChallenge(lur2.ID).Execute() require.Error(t, err) } func compareSDKLoginRequest(t *testing.T, expected *LoginRequest, got hydra.OAuth2LoginRequest) { assert.EqualValues(t, expected.ID, got.Challenge) assert.EqualValues(t, expected.Subject, got.Subject) assert.EqualValues(t, expected.Skip, got.Skip) assert.EqualValues(t, expected.Client.GetID(), *got.Client.ClientId) } func compareSDKConsentRequest(t *testing.T, expected *OAuth2ConsentRequest, got hydra.OAuth2ConsentRequest) { assert.EqualValues(t, expected.ID, got.Challenge) assert.EqualValues(t, expected.Subject, *got.Subject) assert.EqualValues(t, expected.Skip, *got.Skip) assert.EqualValues(t, expected.Client.GetID(), *got.Client.ClientId) } func compareSDKLogoutRequest(t *testing.T, expected *LogoutRequest, got *hydra.OAuth2LogoutRequest) { assert.EqualValues(t, expected.Subject, *got.Subject) assert.EqualValues(t, expected.SessionID, *got.Sid) assert.EqualValues(t, expected.SessionID, *got.Sid) assert.EqualValues(t, expected.RequestURL, *got.RequestUrl) assert.EqualValues(t, expected.RPInitiated, *got.RpInitiated) } type executer[T any] interface { Execute() (*T, *http.Response, error) } func execute[T any](t *testing.T, e executer[T]) *T { got, res, err := e.Execute() require.NoError(t, err) require.NoError(t, res.Body.Close()) return got }
Go
hydra/consent/strategy.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "context" "net/http" "github.com/ory/fosite" "github.com/ory/hydra/v2/flow" ) var _ Strategy = new(DefaultStrategy) type Strategy interface { HandleOAuth2AuthorizationRequest( ctx context.Context, w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, ) (*flow.AcceptOAuth2ConsentRequest, *flow.Flow, error) HandleOpenIDConnectLogout(ctx context.Context, w http.ResponseWriter, r *http.Request) (*flow.LogoutResult, error) HandleHeadlessLogout(ctx context.Context, w http.ResponseWriter, r *http.Request, sid string) error ObfuscateSubjectIdentifier(ctx context.Context, cl fosite.Client, subject, forcedIdentifier string) (string, error) }
Go
hydra/consent/strategy_default.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "context" "fmt" "net/http" "net/url" "strconv" "strings" "time" "github.com/gorilla/sessions" "github.com/hashicorp/go-retryablehttp" "github.com/pborman/uuid" "github.com/pkg/errors" "github.com/sirupsen/logrus" "go.opentelemetry.io/otel/trace" "github.com/ory/hydra/v2/flow" "github.com/ory/hydra/v2/oauth2/flowctx" "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" "github.com/ory/fosite/token/jwt" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/x" "github.com/ory/x/errorsx" "github.com/ory/x/mapx" "github.com/ory/x/otelx" "github.com/ory/x/sqlcon" "github.com/ory/x/sqlxx" "github.com/ory/x/stringslice" "github.com/ory/x/stringsx" "github.com/ory/x/urlx" ) const ( CookieAuthenticationSIDName = "sid" ) type DefaultStrategy struct { c *config.DefaultProvider r InternalRegistry } func NewStrategy( r InternalRegistry, c *config.DefaultProvider, ) *DefaultStrategy { return &DefaultStrategy{ c: c, r: r, } } var ErrAbortOAuth2Request = errors.New("the OAuth 2.0 Authorization request must be aborted") var ErrNoPreviousConsentFound = errors.New("no previous OAuth 2.0 Consent could be found for this access request") var ErrNoAuthenticationSessionFound = errors.New("no previous login session was found") var ErrHintDoesNotMatchAuthentication = errors.New("subject from hint does not match subject from session") func (s *DefaultStrategy) matchesValueFromSession(ctx context.Context, c fosite.Client, hintSubject string, sessionSubject string) error { obfuscatedUserID, err := s.ObfuscateSubjectIdentifier(ctx, c, sessionSubject, "") if err != nil { return err } var forcedObfuscatedUserID string if s, err := s.r.ConsentManager().GetForcedObfuscatedLoginSession(ctx, c.GetID(), hintSubject); errors.Is(err, x.ErrNotFound) { // do nothing } else if err != nil { return err } else { forcedObfuscatedUserID = s.SubjectObfuscated } if hintSubject != sessionSubject && hintSubject != obfuscatedUserID && hintSubject != forcedObfuscatedUserID { return ErrHintDoesNotMatchAuthentication } return nil } func (s *DefaultStrategy) authenticationSession(ctx context.Context, _ http.ResponseWriter, r *http.Request) (*flow.LoginSession, error) { store, err := s.r.CookieStore(ctx) if err != nil { return nil, err } // We try to open the session cookie. If it does not exist (indicated by the error), we must authenticate the user. cookie, err := store.Get(r, s.c.SessionCookieName(ctx)) if err != nil { s.r.Logger(). WithRequest(r). WithError(err).Debug("User logout skipped because cookie store returned an error.") return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound) } sessionID := mapx.GetStringDefault(cookie.Values, CookieAuthenticationSIDName, "") if sessionID == "" { s.r.Logger(). WithRequest(r). Debug("User logout skipped because cookie exists but session value is empty.") return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound) } sessionFromCookie := s.loginSessionFromCookie(r) session, err := s.r.ConsentManager().GetRememberedLoginSession(r.Context(), sessionFromCookie, sessionID) if errors.Is(err, x.ErrNotFound) { s.r.Logger().WithRequest(r).WithError(err). Debug("User logout skipped because cookie exists and session value exist but are not remembered any more.") return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound) } else if err != nil { return nil, err } return session, nil } func (s *DefaultStrategy) requestAuthentication(ctx context.Context, w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester) (err error) { ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.requestAuthentication") defer otelx.End(span, &err) prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") if stringslice.Has(prompt, "login") { return s.forwardAuthenticationRequest(ctx, w, r, ar, "", time.Time{}, nil) } session, err := s.authenticationSession(ctx, w, r) if errors.Is(err, ErrNoAuthenticationSessionFound) { return s.forwardAuthenticationRequest(ctx, w, r, ar, "", time.Time{}, nil) } else if err != nil { return err } maxAge := int64(-1) if ma := ar.GetRequestForm().Get("max_age"); len(ma) > 0 { var err error maxAge, err = strconv.ParseInt(ma, 10, 64) if err != nil { return err } } if maxAge > -1 && time.Time(session.AuthenticatedAt).UTC().Add(time.Second*time.Duration(maxAge)).Before(time.Now().UTC()) { if stringslice.Has(prompt, "none") { return errorsx.WithStack(fosite.ErrLoginRequired.WithHint("Request failed because prompt is set to 'none' and authentication time reached 'max_age'.")) } return s.forwardAuthenticationRequest(ctx, w, r, ar, "", time.Time{}, nil) } idTokenHint := ar.GetRequestForm().Get("id_token_hint") if idTokenHint == "" { return s.forwardAuthenticationRequest(ctx, w, r, ar, session.Subject, time.Time(session.AuthenticatedAt), session) } hintSub, err := s.getSubjectFromIDTokenHint(r.Context(), idTokenHint) if err != nil { return err } if err := s.matchesValueFromSession(r.Context(), ar.GetClient(), hintSub, session.Subject); errors.Is(err, ErrHintDoesNotMatchAuthentication) { return errorsx.WithStack(fosite.ErrLoginRequired.WithHint("Request failed because subject claim from id_token_hint does not match subject from authentication session.")) } return s.forwardAuthenticationRequest(ctx, w, r, ar, session.Subject, time.Time(session.AuthenticatedAt), session) } func (s *DefaultStrategy) getIDTokenHintClaims(ctx context.Context, idTokenHint string) (jwt.MapClaims, error) { token, err := s.r.OpenIDJWTStrategy().Decode(ctx, idTokenHint) if ve := new(jwt.ValidationError); errors.As(err, &ve) && ve.Errors == jwt.ValidationErrorExpired { // Expired is ok } else if err != nil { return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(err.Error())) } return token.Claims, nil } func (s *DefaultStrategy) getSubjectFromIDTokenHint(ctx context.Context, idTokenHint string) (string, error) { claims, err := s.getIDTokenHintClaims(ctx, idTokenHint) if err != nil { return "", err } sub, _ := claims["sub"].(string) if sub == "" { return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Failed to validate OpenID Connect request because provided id token from id_token_hint does not have a subject.")) } return sub, nil } func (s *DefaultStrategy) forwardAuthenticationRequest(ctx context.Context, w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, subject string, authenticatedAt time.Time, session *flow.LoginSession) error { if (subject != "" && authenticatedAt.IsZero()) || (subject == "" && !authenticatedAt.IsZero()) { return errorsx.WithStack(fosite.ErrServerError.WithHint("Consent strategy returned a non-empty subject with an empty auth date, or an empty subject with a non-empty auth date.")) } skip := false if subject != "" { skip = true } // Let'id validate that prompt is actually not "none" if we can't skip authentication prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") if stringslice.Has(prompt, "none") && !skip { return errorsx.WithStack(fosite.ErrLoginRequired.WithHint(`Prompt 'none' was requested, but no existing login session was found.`)) } // Set up csrf/challenge/verifier values verifier := strings.Replace(uuid.New(), "-", "", -1) challenge := strings.Replace(uuid.New(), "-", "", -1) csrf := strings.Replace(uuid.New(), "-", "", -1) // Generate the request URL iu := s.c.OAuth2AuthURL(ctx) iu.RawQuery = r.URL.RawQuery var idTokenHintClaims jwt.MapClaims if idTokenHint := ar.GetRequestForm().Get("id_token_hint"); len(idTokenHint) > 0 { claims, err := s.getIDTokenHintClaims(r.Context(), idTokenHint) if err != nil { return err } idTokenHintClaims = claims } sessionID := uuid.New() if session != nil { sessionID = session.ID } else { // Create a stub session so that we can later update it. loginSession := &flow.LoginSession{ID: sessionID} if err := s.r.ConsentManager().CreateLoginSession(ctx, loginSession); err != nil { return err } if err := flowctx.SetCookie(ctx, w, s.r, flowctx.LoginSessionCookie(flowctx.SuffixForClient(ar.GetClient())), loginSession); err != nil { return err } } // Set the session cl := sanitizeClientFromRequest(ar) loginRequest := &flow.LoginRequest{ ID: challenge, Verifier: verifier, CSRF: csrf, Skip: skip, RequestedScope: []string(ar.GetRequestedScopes()), RequestedAudience: []string(ar.GetRequestedAudience()), Subject: subject, Client: cl, RequestURL: iu.String(), AuthenticatedAt: sqlxx.NullTime(authenticatedAt), RequestedAt: time.Now().Truncate(time.Second).UTC(), SessionID: sqlxx.NullString(sessionID), OpenIDConnectContext: &flow.OAuth2ConsentRequestOpenIDConnectContext{ IDTokenHintClaims: idTokenHintClaims, ACRValues: stringsx.Splitx(ar.GetRequestForm().Get("acr_values"), " "), UILocales: stringsx.Splitx(ar.GetRequestForm().Get("ui_locales"), " "), Display: ar.GetRequestForm().Get("display"), LoginHint: ar.GetRequestForm().Get("login_hint"), }, } f, err := s.r.ConsentManager().CreateLoginRequest( ctx, loginRequest, ) if err != nil { return errorsx.WithStack(err) } if err := flowctx.SetCookie(ctx, w, s.r, flowctx.FlowCookie(cl), f); err != nil { return err } store, err := s.r.CookieStore(ctx) if err != nil { return err } clientSpecificCookieNameLoginCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameLoginCSRF(ctx), cl.CookieSuffix()) if err := createCsrfSession(w, r, s.r.Config(), store, clientSpecificCookieNameLoginCSRF, csrf, s.c.ConsentRequestMaxAge(ctx)); err != nil { return errorsx.WithStack(err) } encodedFlow, err := f.ToLoginChallenge(ctx, s.r) if err != nil { return err } http.Redirect(w, r, urlx.SetQuery(s.c.LoginURL(ctx), url.Values{"login_challenge": {encodedFlow}}).String(), http.StatusFound) // generate the verifier return errorsx.WithStack(ErrAbortOAuth2Request) } func (s *DefaultStrategy) revokeAuthenticationSession(ctx context.Context, w http.ResponseWriter, r *http.Request) error { store, err := s.r.CookieStore(ctx) if err != nil { return err } sid, err := s.revokeAuthenticationCookie(w, r, store) if err != nil { return err } if sid == "" { return nil } _, err = s.r.ConsentManager().DeleteLoginSession(r.Context(), sid) return err } func (s *DefaultStrategy) revokeAuthenticationCookie(w http.ResponseWriter, r *http.Request, ss sessions.Store) (string, error) { ctx := r.Context() cookie, _ := ss.Get(r, s.c.SessionCookieName(ctx)) sid, _ := mapx.GetString(cookie.Values, CookieAuthenticationSIDName) cookie.Values[CookieAuthenticationSIDName] = "" cookie.Options.HttpOnly = true cookie.Options.Path = s.c.SessionCookiePath(ctx) cookie.Options.SameSite = s.c.CookieSameSiteMode(ctx) cookie.Options.Secure = s.c.CookieSecure(ctx) cookie.Options.Domain = s.c.CookieDomain(ctx) cookie.Options.MaxAge = -1 if err := cookie.Save(r, w); err != nil { return "", errorsx.WithStack(err) } return sid, nil } func (s *DefaultStrategy) verifyAuthentication( ctx context.Context, w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string, ) (_ *flow.Flow, err error) { ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.verifyAuthentication") defer otelx.End(span, &err) f, err := s.flowFromCookie(r) if err != nil { return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The flow cookie is missing in the request.")) } if f.Client.GetID() != req.GetClient().GetID() { return nil, errorsx.WithStack(fosite.ErrInvalidClient.WithHint("The flow cookie client id does not match the authorize request client id.")) } session, err := s.r.ConsentManager().VerifyAndInvalidateLoginRequest(ctx, f, verifier) if errors.Is(err, sqlcon.ErrNoRows) { return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The login verifier has already been used, has not been granted, or is invalid.")) } else if err != nil { return nil, err } if session.HasError() { session.Error.SetDefaults(flow.LoginRequestDeniedErrorName) return nil, errorsx.WithStack(session.Error.ToRFCError()) } if session.RequestedAt.Add(s.c.ConsentRequestMaxAge(ctx)).Before(time.Now()) { return nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The login request has expired. Please try again.")) } store, err := s.r.CookieStore(ctx) if err != nil { return nil, err } clientSpecificCookieNameLoginCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameLoginCSRF(ctx), session.LoginRequest.Client.CookieSuffix()) if err := validateCsrfSession(r, s.r.Config(), store, clientSpecificCookieNameLoginCSRF, session.LoginRequest.CSRF); err != nil { return nil, err } if session.LoginRequest.Skip && !session.Remember { return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The login request was previously remembered and can only be forgotten using the reject feature.")) } if session.LoginRequest.Skip && session.Subject != session.LoginRequest.Subject { // Revoke the session because there's clearly a mix up wrt the subject that's being authenticated if err := s.revokeAuthenticationSession(ctx, w, r); err != nil { return nil, err } return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The login request is marked as remember, but the subject from the login confirmation does not match the original subject from the cookie.")) } subjectIdentifier, err := s.ObfuscateSubjectIdentifier(ctx, req.GetClient(), session.Subject, session.ForceSubjectIdentifier) if err != nil { return nil, err } sessionID := session.LoginRequest.SessionID.String() if err := s.r.OpenIDConnectRequestValidator().ValidatePrompt(ctx, &fosite.AuthorizeRequest{ ResponseTypes: req.GetResponseTypes(), RedirectURI: req.GetRedirectURI(), State: req.GetState(), // HandledResponseTypes, this can be safely ignored because it's not being used by validation Request: fosite.Request{ ID: req.GetID(), RequestedAt: req.GetRequestedAt(), Client: req.GetClient(), RequestedAudience: req.GetRequestedAudience(), GrantedAudience: req.GetGrantedAudience(), RequestedScope: req.GetRequestedScopes(), GrantedScope: req.GetGrantedScopes(), Form: req.GetRequestForm(), Session: &openid.DefaultSession{ Claims: &jwt.IDTokenClaims{ Subject: subjectIdentifier, IssuedAt: time.Now().UTC(), // doesn't matter ExpiresAt: time.Now().Add(time.Hour).UTC(), // doesn't matter AuthTime: time.Time(session.AuthenticatedAt), RequestedAt: session.RequestedAt, }, Headers: &jwt.Headers{}, Subject: session.Subject, }, }, }); errors.Is(err, fosite.ErrLoginRequired) { // This indicates that something went wrong with checking the subject id - let's destroy the session to be safe if err := s.revokeAuthenticationSession(ctx, w, r); err != nil { return nil, err } return nil, err } else if err != nil { return nil, err } if session.ForceSubjectIdentifier != "" { if err := s.r.ConsentManager().CreateForcedObfuscatedLoginSession(r.Context(), &ForcedObfuscatedLoginSession{ Subject: session.Subject, ClientID: req.GetClient().GetID(), SubjectObfuscated: session.ForceSubjectIdentifier, }); err != nil { return nil, err } } if !session.LoginRequest.Skip { if time.Time(session.AuthenticatedAt).IsZero() { return nil, errorsx.WithStack(fosite.ErrServerError.WithHint( "Expected the handled login request to contain a valid authenticated_at value but it was zero. This is a bug which should be reported to https://github.com/ory/hydra.")) } loginSession := s.loginSessionFromCookie(r) if loginSession == nil { return nil, fosite.ErrAccessDenied.WithHint("The login session cookie was not found or malformed.") } loginSession.IdentityProviderSessionID = sqlxx.NullString(session.IdentityProviderSessionID) if err := s.r.ConsentManager().ConfirmLoginSession(ctx, loginSession, sessionID, time.Time(session.AuthenticatedAt), session.Subject, session.Remember); err != nil { return nil, err } } if !session.Remember && !session.LoginRequest.Skip { // If the session should not be remembered (and we're actually not skipping), than the user clearly don't // wants us to store a cookie. So let's bust the authentication session (if one exists). if err := s.revokeAuthenticationSession(ctx, w, r); err != nil { return nil, err } } if !session.Remember || session.LoginRequest.Skip && !session.ExtendSessionLifespan { // If the user doesn't want to remember the session, we do not store a cookie. // If login was skipped, it means an authentication cookie was present and // we don't want to touch it (in order to preserve its original expiry date) return f, nil } // Not a skipped login and the user asked to remember its session, store a cookie cookie, _ := store.Get(r, s.c.SessionCookieName(ctx)) cookie.Values[CookieAuthenticationSIDName] = sessionID if session.RememberFor >= 0 { cookie.Options.MaxAge = session.RememberFor } cookie.Options.HttpOnly = true cookie.Options.Path = s.c.SessionCookiePath(ctx) cookie.Options.SameSite = s.c.CookieSameSiteMode(ctx) cookie.Options.Secure = s.c.CookieSecure(ctx) if err := cookie.Save(r, w); err != nil { return nil, errorsx.WithStack(err) } s.r.Logger().WithRequest(r). WithFields(logrus.Fields{ "cookie_name": s.c.SessionCookieName(ctx), "cookie_http_only": true, "cookie_same_site": s.c.CookieSameSiteMode(ctx), "cookie_secure": s.c.CookieSecure(ctx), }).Debug("Authentication session cookie was set.") if err = flowctx.SetCookie(ctx, w, s.r, flowctx.FlowCookie(flowctx.SuffixForClient(req.GetClient())), f); err != nil { return nil, errorsx.WithStack(err) } return f, nil } func (s *DefaultStrategy) requestConsent( ctx context.Context, w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, f *flow.Flow, ) (err error) { ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.requestConsent") defer otelx.End(span, &err) prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") if stringslice.Has(prompt, "consent") { return s.forwardConsentRequest(ctx, w, r, ar, f, nil) } // https://tools.ietf.org/html/rfc6749 // // As stated in Section 10.2 of OAuth 2.0 [RFC6749], the authorization // server SHOULD NOT process authorization requests automatically // without user consent or interaction, except when the identity of the // client can be assured. This includes the case where the user has // previously approved an authorization request for a given client id -- // unless the identity of the client can be proven, the request SHOULD // be processed as if no previous request had been approved. // // Measures such as claimed "https" scheme redirects MAY be accepted by // authorization servers as identity proof. Some operating systems may // offer alternative platform-specific identity features that MAY be // accepted, as appropriate. if ar.GetClient().IsPublic() { // The OpenID Connect Test Tool fails if this returns `consent_required` when `prompt=none` is used. // According to the quote above, it should be ok to allow https to skip consent. // // This is tracked as issue: https://github.com/ory/hydra/issues/866 // This is also tracked as upstream issue: https://github.com/openid-certification/oidctest/issues/97 if !(ar.GetRedirectURI().Scheme == "https" || (fosite.IsLocalhost(ar.GetRedirectURI()) && ar.GetRedirectURI().Scheme == "http")) { return s.forwardConsentRequest(ctx, w, r, ar, f, nil) } } // This breaks OIDC Conformity Tests and is probably a bit paranoid. // // if ar.GetResponseTypes().Has("token") { // // We're probably requesting the implicit or hybrid flow in which case we MUST authenticate and authorize the request // return s.forwardConsentRequest(w, r, ar, authenticationSession, nil) // } consentSessions, err := s.r.ConsentManager().FindGrantedAndRememberedConsentRequests(ctx, ar.GetClient().GetID(), f.Subject) if errors.Is(err, ErrNoPreviousConsentFound) { return s.forwardConsentRequest(ctx, w, r, ar, f, nil) } else if err != nil { return err } if found := matchScopes(s.r.Config().GetScopeStrategy(ctx), consentSessions, ar.GetRequestedScopes()); found != nil { return s.forwardConsentRequest(ctx, w, r, ar, f, found) } return s.forwardConsentRequest(ctx, w, r, ar, f, nil) } func (s *DefaultStrategy) forwardConsentRequest( ctx context.Context, w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, f *flow.Flow, previousConsent *flow.AcceptOAuth2ConsentRequest, ) error { as := f.GetHandledLoginRequest() skip := false if previousConsent != nil { skip = true } prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") if stringslice.Has(prompt, "none") && !skip { return errorsx.WithStack(fosite.ErrConsentRequired.WithHint(`Prompt 'none' was requested, but no previous consent was found.`)) } // Set up csrf/challenge/verifier values verifier := strings.Replace(uuid.New(), "-", "", -1) challenge := strings.Replace(uuid.New(), "-", "", -1) csrf := strings.Replace(uuid.New(), "-", "", -1) cl := sanitizeClientFromRequest(ar) consentRequest := &flow.OAuth2ConsentRequest{ ID: challenge, ACR: as.ACR, AMR: as.AMR, Verifier: verifier, CSRF: csrf, Skip: skip, RequestedScope: []string(ar.GetRequestedScopes()), RequestedAudience: []string(ar.GetRequestedAudience()), Subject: as.Subject, Client: cl, RequestURL: as.LoginRequest.RequestURL, AuthenticatedAt: as.AuthenticatedAt, RequestedAt: as.RequestedAt, ForceSubjectIdentifier: as.ForceSubjectIdentifier, OpenIDConnectContext: as.LoginRequest.OpenIDConnectContext, LoginSessionID: as.LoginRequest.SessionID, LoginChallenge: sqlxx.NullString(as.LoginRequest.ID), Context: as.Context, } err := s.r.ConsentManager().CreateConsentRequest(ctx, f, consentRequest) if err != nil { return errorsx.WithStack(err) } if err := flowctx.SetCookie(ctx, w, s.r, flowctx.FlowCookie(cl), f); err != nil { return err } consentChallenge, err := f.ToConsentChallenge(ctx, s.r) if err != nil { return err } store, err := s.r.CookieStore(ctx) if err != nil { return err } clientSpecificCookieNameConsentCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameConsentCSRF(ctx), cl.CookieSuffix()) if err := createCsrfSession(w, r, s.r.Config(), store, clientSpecificCookieNameConsentCSRF, csrf, s.c.ConsentRequestMaxAge(ctx)); err != nil { return errorsx.WithStack(err) } http.Redirect( w, r, urlx.SetQuery(s.c.ConsentURL(ctx), url.Values{"consent_challenge": {consentChallenge}}).String(), http.StatusFound, ) // generate the verifier return errorsx.WithStack(ErrAbortOAuth2Request) } func (s *DefaultStrategy) verifyConsent(ctx context.Context, w http.ResponseWriter, r *http.Request, verifier string) (_ *flow.AcceptOAuth2ConsentRequest, _ *flow.Flow, err error) { ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.verifyConsent") defer otelx.End(span, &err) f, err := s.flowFromCookie(r) if err != nil { return nil, nil, err } if f.Client.GetID() != r.URL.Query().Get("client_id") { return nil, nil, errorsx.WithStack(fosite.ErrInvalidClient.WithHint("The flow cookie client id does not match the authorize request client id.")) } session, err := s.r.ConsentManager().VerifyAndInvalidateConsentRequest(ctx, f, verifier) if errors.Is(err, sqlcon.ErrNoRows) { return nil, nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The consent verifier has already been used, has not been granted, or is invalid.")) } else if err != nil { return nil, nil, err } if session.RequestedAt.Add(s.c.ConsentRequestMaxAge(ctx)).Before(time.Now()) { return nil, nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The consent request has expired, please try again.")) } if session.HasError() { session.Error.SetDefaults(flow.ConsentRequestDeniedErrorName) return nil, nil, errorsx.WithStack(session.Error.ToRFCError()) } if time.Time(session.ConsentRequest.AuthenticatedAt).IsZero() { return nil, nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The authenticatedAt value was not set.")) } store, err := s.r.CookieStore(ctx) if err != nil { return nil, nil, err } clientSpecificCookieNameConsentCSRF := fmt.Sprintf("%s_%s", s.r.Config().CookieNameConsentCSRF(ctx), session.ConsentRequest.Client.CookieSuffix()) if err := validateCsrfSession(r, s.r.Config(), store, clientSpecificCookieNameConsentCSRF, session.ConsentRequest.CSRF); err != nil { return nil, nil, err } if err = flowctx.DeleteCookie(ctx, w, s.r, flowctx.FlowCookie(f.Client)); err != nil { return nil, nil, err } if session.Session == nil { session.Session = flow.NewConsentRequestSessionData() } if session.Session.AccessToken == nil { session.Session.AccessToken = map[string]interface{}{} } if session.Session.IDToken == nil { session.Session.IDToken = map[string]interface{}{} } session.AuthenticatedAt = session.ConsentRequest.AuthenticatedAt return session, f, nil } func (s *DefaultStrategy) generateFrontChannelLogoutURLs(ctx context.Context, subject, sid string) ([]string, error) { clients, err := s.r.ConsentManager().ListUserAuthenticatedClientsWithFrontChannelLogout(ctx, subject, sid) if err != nil { return nil, err } var urls []string for _, c := range clients { u, err := url.Parse(c.FrontChannelLogoutURI) if err != nil { return nil, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unable to parse frontchannel_logout_uri because %s.", c.FrontChannelLogoutURI).WithDebug(err.Error())) } urls = append(urls, urlx.SetQuery(u, url.Values{ "iss": {s.c.IssuerURL(ctx).String()}, "sid": {sid}, }).String()) } return urls, nil } func (s *DefaultStrategy) executeBackChannelLogout(r *http.Request, subject, sid string) error { ctx := r.Context() clients, err := s.r.ConsentManager().ListUserAuthenticatedClientsWithBackChannelLogout(ctx, subject, sid) if err != nil { return err } openIDKeyID, err := s.r.OpenIDJWTStrategy().GetPublicKeyID(ctx) if err != nil { return err } type task struct { url string token string clientID string } var tasks []task for _, c := range clients { // Getting the forced obfuscated login session is tricky because the user id could be obfuscated with a new // ID every time the algorithm is used. Thus, we would only get the most recent version. It therefore makes // sense to just use the sid. // // s.r.ConsentManager().GetForcedObfuscatedLoginSession(context.Background(), subject, <missing>) // sub := s.obfuscateSubjectIdentifier(c, subject, ) t, _, err := s.r.OpenIDJWTStrategy().Generate(ctx, jwt.MapClaims{ "iss": s.c.IssuerURL(ctx).String(), "aud": []string{c.LegacyClientID}, "iat": time.Now().UTC().Unix(), "jti": uuid.New(), "events": map[string]struct{}{"http://schemas.openid.net/event/backchannel-logout": {}}, "sid": sid, }, &jwt.Headers{ Extra: map[string]interface{}{"kid": openIDKeyID}, }) if err != nil { return err } tasks = append(tasks, task{url: c.BackChannelLogoutURI, clientID: c.GetID(), token: t}) } span := trace.SpanFromContext(ctx) cl := s.r.HTTPClient(ctx) execute := func(t task) { log := s.r.Logger().WithRequest(r). WithField("client_id", t.clientID). WithField("backchannel_logout_url", t.url) body := url.Values{"logout_token": {t.token}}.Encode() req, err := retryablehttp.NewRequestWithContext(trace.ContextWithSpan(context.Background(), span), "POST", t.url, []byte(body)) if err != nil { log.WithError(err).Error("Unable to construct OpenID Connect Back-Channel Logout Request") return } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") res, err := cl.Do(req) if err != nil { log.WithError(err).Error("Unable to execute OpenID Connect Back-Channel Logout Request") return } defer res.Body.Close() if res.StatusCode != http.StatusOK { log.WithError(errors.Errorf("expected HTTP status code %d but got %d", http.StatusOK, res.StatusCode)). Error("Unable to execute OpenID Connect Back-Channel Logout Request") return } else { log.Info("Back-Channel Logout Request") } } for _, t := range tasks { go execute(t) } return nil } func (s *DefaultStrategy) issueLogoutVerifier(ctx context.Context, w http.ResponseWriter, r *http.Request) (*flow.LogoutResult, error) { // There are two types of log out flows: // // - RP initiated logout // - OP initiated logout // Per default, we're redirecting to the global redirect URL. This is assuming that we're not an RP-initiated // logout flow. redir := s.c.LogoutRedirectURL(ctx).String() if err := r.ParseForm(); err != nil { return nil, errorsx.WithStack(fosite.ErrInvalidRequest. WithHintf("Logout failed because the '%s' request could not be parsed.", r.Method), ) } hint := r.Form.Get("id_token_hint") state := r.Form.Get("state") requestedRedir := r.Form.Get("post_logout_redirect_uri") if len(hint) == 0 { // hint is not set, so this is an OP initiated logout if len(state) > 0 { // state can only be set if it's an RP-initiated logout flow. If not, we should throw an error. return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter state is set but id_token_hint is missing.")) } if len(requestedRedir) > 0 { // post_logout_redirect_uri can only be set if it's an RP-initiated logout flow. If not, we should throw an error. return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter post_logout_redirect_uri is set but id_token_hint is missing.")) } session, err := s.authenticationSession(ctx, w, r) if errors.Is(err, ErrNoAuthenticationSessionFound) { // OP initiated log out but no session was found. Since we can not identify the user we can not call // any RPs. s.r.AuditLogger(). WithRequest(r). Info("User logout skipped because no authentication session exists.") http.Redirect(w, r, redir, http.StatusFound) return nil, errorsx.WithStack(ErrAbortOAuth2Request) } else if err != nil { return nil, err } challenge := uuid.New() if err := s.r.ConsentManager().CreateLogoutRequest(r.Context(), &flow.LogoutRequest{ RequestURL: r.URL.String(), ID: challenge, Subject: session.Subject, SessionID: session.ID, Verifier: uuid.New(), RPInitiated: false, // PostLogoutRedirectURI is set to the value from config.Provider().LogoutRedirectURL() PostLogoutRedirectURI: redir, }); err != nil { return nil, err } s.r.AuditLogger(). WithRequest(r). Info("User logout requires user confirmation, redirecting to Logout UI.") http.Redirect(w, r, urlx.SetQuery(s.c.LogoutURL(ctx), url.Values{"logout_challenge": {challenge}}).String(), http.StatusFound) return nil, errorsx.WithStack(ErrAbortOAuth2Request) } claims, err := s.getIDTokenHintClaims(r.Context(), hint) if err != nil { return nil, err } mksi := mapx.KeyStringToInterface(claims) if !claims.VerifyIssuer(s.c.IssuerURL(ctx).String(), true) { return nil, errorsx.WithStack(fosite.ErrInvalidRequest. WithHintf( `Logout failed because issuer claim value '%s' from query parameter id_token_hint does not match with issuer value from configuration '%s'.`, mapx.GetStringDefault(mksi, "iss", ""), s.c.IssuerURL(ctx).String(), ), ) } now := time.Now().UTC().Unix() if !claims.VerifyIssuedAt(now, true) { return nil, errorsx.WithStack(fosite.ErrInvalidRequest. WithHintf( `Logout failed because iat claim value '%.0f' from query parameter id_token_hint is before now ('%d').`, mapx.GetFloat64Default(mksi, "iat", float64(0)), now, ), ) } hintSid := mapx.GetStringDefault(mksi, "sid", "") if len(hintSid) == 0 { return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter id_token_hint is missing sid claim.")) } // It doesn't really make sense to use the subject value from the ID Token because it might be obfuscated. if hintSub := mapx.GetStringDefault(mksi, "sub", ""); len(hintSub) == 0 { return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter id_token_hint is missing sub claim.")) } // Let's find the client by cycling through the audiences. Typically, we only have one audience var cl *client.Client for _, aud := range mapx.GetStringSliceDefault( mksi, "aud", []string{ mapx.GetStringDefault(mksi, "aud", ""), }, ) { c, err := s.r.ClientManager().GetConcreteClient(r.Context(), aud) if errors.Is(err, x.ErrNotFound) { continue } else if err != nil { return nil, err } cl = c break } if cl == nil { return nil, errorsx.WithStack(fosite.ErrInvalidRequest. WithHint("Logout failed because none of the listed audiences is a registered OAuth 2.0 Client.")) } if len(requestedRedir) > 0 { var f *url.URL for _, w := range cl.PostLogoutRedirectURIs { if w == requestedRedir { u, err := url.Parse(w) if err != nil { return nil, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unable to parse post_logout_redirect_uri '%s'.", w).WithDebug(err.Error())) } f = u } } if f == nil { return nil, errorsx.WithStack(fosite.ErrInvalidRequest. WithHint("Logout failed because query parameter post_logout_redirect_uri is not a whitelisted as a post_logout_redirect_uri for the client."), ) } params := url.Values{} if state != "" { params.Add("state", state) } redir = urlx.SetQuery(f, params).String() } // We do not really want to verify if the user (from id token hint) has a session here because it doesn't really matter. // Instead, we'll check this when we're actually revoking the cookie! sessionFromCookie := s.loginSessionFromCookie(r) session, err := s.r.ConsentManager().GetRememberedLoginSession(r.Context(), sessionFromCookie, hintSid) if errors.Is(err, x.ErrNotFound) { // Such a session does not exist - maybe it has already been revoked? In any case, we can't do much except // leaning back and redirecting back. http.Redirect(w, r, redir, http.StatusFound) return nil, errorsx.WithStack(ErrAbortOAuth2Request) } else if err != nil { return nil, err } challenge := uuid.New() if err := s.r.ConsentManager().CreateLogoutRequest(r.Context(), &flow.LogoutRequest{ RequestURL: r.URL.String(), ID: challenge, SessionID: hintSid, Subject: session.Subject, Verifier: uuid.New(), Client: cl, RPInitiated: true, // PostLogoutRedirectURI is set to the value from config.Provider().LogoutRedirectURL() PostLogoutRedirectURI: redir, }); err != nil { return nil, err } http.Redirect(w, r, urlx.SetQuery(s.c.LogoutURL(ctx), url.Values{"logout_challenge": {challenge}}).String(), http.StatusFound) return nil, errorsx.WithStack(ErrAbortOAuth2Request) } func (s *DefaultStrategy) performBackChannelLogoutAndDeleteSession(r *http.Request, subject string, sid string) error { ctx := r.Context() if err := s.executeBackChannelLogout(r, subject, sid); err != nil { return err } // We delete the session after back channel log out has worked as the session is otherwise removed // from the store which will break the query for finding all the channels. // // executeBackChannelLogout only fails on system errors so not on URL errors, so this should be fine // even if an upstream URL fails! if session, err := s.r.ConsentManager().DeleteLoginSession(ctx, sid); errors.Is(err, sqlcon.ErrNoRows) { // This is ok (session probably already revoked), do nothing! } else if err != nil { return err } else { innerErr := s.r.Kratos().DisableSession(ctx, session.IdentityProviderSessionID.String()) if innerErr != nil { s.r.Logger().WithError(innerErr).WithField("sid", sid).Error("Unable to revoke session in ORY Kratos.") } // We don't return the error here because we don't want to break the logout flow if Kratos is down. } return nil } func (s *DefaultStrategy) completeLogout(ctx context.Context, w http.ResponseWriter, r *http.Request) (*flow.LogoutResult, error) { verifier := r.URL.Query().Get("logout_verifier") lr, err := s.r.ConsentManager().VerifyAndInvalidateLogoutRequest(r.Context(), verifier) if err != nil { return nil, err } if !lr.RPInitiated { // If this is true it means that no id_token_hint was given, so the session id and subject id // came from an original cookie. session, err := s.authenticationSession(ctx, w, r) if errors.Is(err, ErrNoAuthenticationSessionFound) { // If we end up here it means that the cookie was revoked between the initial logout request // and ending up here - possibly due to a duplicate submit. In that case, we really have nothing to // do because the logout was already completed, apparently! // We also won't call any front- or back-channel logouts because that would mean we had called them twice! // OP initiated log out but no session was found. So let's just redirect back... http.Redirect(w, r, lr.PostLogoutRedirectURI, http.StatusFound) return nil, errorsx.WithStack(ErrAbortOAuth2Request) } else if err != nil { return nil, err } if session.Subject != lr.Subject { // If we end up here it means that the authentication cookie changed between the initial logout request // and landing here. That could happen because the user signed in in another browser window. In that // case there isn't really a lot to do because we don't want to sign out a different ID, so let's just // go to the post redirect uri without actually doing anything! http.Redirect(w, r, lr.PostLogoutRedirectURI, http.StatusFound) return nil, errorsx.WithStack(ErrAbortOAuth2Request) } } store, err := s.r.CookieStore(ctx) if err != nil { return nil, err } _, _ = s.revokeAuthenticationCookie(w, r, store) // Cookie removal is optional urls, err := s.generateFrontChannelLogoutURLs(r.Context(), lr.Subject, lr.SessionID) if err != nil { return nil, err } if err := s.performBackChannelLogoutAndDeleteSession(r, lr.Subject, lr.SessionID); err != nil { return nil, err } s.r.AuditLogger(). WithRequest(r). WithField("subject", lr.Subject). Info("User logout completed!") return &flow.LogoutResult{ RedirectTo: lr.PostLogoutRedirectURI, FrontChannelLogoutURLs: urls, }, nil } func (s *DefaultStrategy) HandleOpenIDConnectLogout(ctx context.Context, w http.ResponseWriter, r *http.Request) (*flow.LogoutResult, error) { verifier := r.URL.Query().Get("logout_verifier") if verifier == "" { return s.issueLogoutVerifier(ctx, w, r) } return s.completeLogout(ctx, w, r) } func (s *DefaultStrategy) HandleHeadlessLogout(ctx context.Context, _ http.ResponseWriter, r *http.Request, sid string) error { sessionFromCookie := s.loginSessionFromCookie(r) loginSession, lsErr := s.r.ConsentManager().GetRememberedLoginSession(ctx, sessionFromCookie, sid) if errors.Is(lsErr, x.ErrNotFound) { // This is ok (session probably already revoked), do nothing! // Not triggering the back-channel logout because subject is not available // See https://github.com/ory/hydra/pull/3450#discussion_r1127798485 return nil } else if lsErr != nil { return lsErr } if err := s.performBackChannelLogoutAndDeleteSession(r, loginSession.Subject, sid); err != nil { return err } s.r.AuditLogger(). WithRequest(r). WithField("subject", loginSession.Subject). WithField("sid", sid). Info("User logout completed via headless flow!") return nil } func (s *DefaultStrategy) HandleOAuth2AuthorizationRequest( ctx context.Context, w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, ) (_ *flow.AcceptOAuth2ConsentRequest, _ *flow.Flow, err error) { ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer("").Start(ctx, "DefaultStrategy.HandleOAuth2AuthorizationRequest") defer otelx.End(span, &err) loginVerifier := strings.TrimSpace(req.GetRequestForm().Get("login_verifier")) consentVerifier := strings.TrimSpace(req.GetRequestForm().Get("consent_verifier")) if loginVerifier == "" && consentVerifier == "" { // ok, we need to process this request and redirect to auth endpoint return nil, nil, s.requestAuthentication(ctx, w, r, req) } else if loginVerifier != "" { f, err := s.verifyAuthentication(ctx, w, r, req, loginVerifier) if err != nil { return nil, nil, err } // ok, we need to process this request and redirect to auth endpoint return nil, f, s.requestConsent(ctx, w, r, req, f) } consentSession, f, err := s.verifyConsent(ctx, w, r, consentVerifier) if err != nil { return nil, nil, err } return consentSession, f, nil } func (s *DefaultStrategy) ObfuscateSubjectIdentifier(ctx context.Context, cl fosite.Client, subject, forcedIdentifier string) (string, error) { if c, ok := cl.(*client.Client); ok && c.SubjectType == "pairwise" { algorithm, ok := s.r.SubjectIdentifierAlgorithm(ctx)[c.SubjectType] if !ok { return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf(`Subject Identifier Algorithm '%s' was requested by OAuth 2.0 Client '%s' but is not configured.`, c.SubjectType, c.GetID())) } if len(forcedIdentifier) > 0 { return forcedIdentifier, nil } return algorithm.Obfuscate(subject, c) } else if !ok { return "", errors.New("Unable to type assert OAuth 2.0 Client to *client.Client") } return subject, nil } func (s *DefaultStrategy) flowFromCookie(r *http.Request) (*flow.Flow, error) { clientID := r.URL.Query().Get("client_id") if clientID == "" { return nil, errors.WithStack(fosite.ErrInvalidClient) } return flowctx.FromCookie[flow.Flow](r.Context(), r, s.r.FlowCipher(), flowctx.FlowCookie(flowctx.SuffixFromStatic(clientID))) } func (s *DefaultStrategy) loginSessionFromCookie(r *http.Request) *flow.LoginSession { clientID := r.URL.Query().Get("client_id") if clientID == "" { return nil } ls, _ := flowctx.FromCookie[flow.LoginSession](r.Context(), r, s.r.FlowCipher(), flowctx.LoginSessionCookie(flowctx.SuffixFromStatic(clientID))) return ls }
Go
hydra/consent/strategy_default_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent_test import ( "context" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "testing" "github.com/google/uuid" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/fosite/token/jwt" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/client" . "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/internal/testhelpers" "github.com/ory/x/ioutilx" "github.com/ory/x/urlx" ) func checkAndAcceptLoginHandler(t *testing.T, apiClient *hydra.APIClient, subject string, cb func(*testing.T, *hydra.OAuth2LoginRequest, error) hydra.AcceptOAuth2LoginRequest) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { res, _, err := apiClient.OAuth2Api.GetOAuth2LoginRequest(context.Background()).LoginChallenge(r.URL.Query().Get("login_challenge")).Execute() payload := cb(t, res, err) payload.Subject = subject v, _, err := apiClient.OAuth2Api.AcceptOAuth2LoginRequest(context.Background()). LoginChallenge(r.URL.Query().Get("login_challenge")). AcceptOAuth2LoginRequest(payload). Execute() require.NoError(t, err) require.NotEmpty(t, v.RedirectTo) http.Redirect(w, r, v.RedirectTo, http.StatusFound) } } func checkAndAcceptConsentHandler(t *testing.T, apiClient *hydra.APIClient, cb func(*testing.T, *hydra.OAuth2ConsentRequest, error) hydra.AcceptOAuth2ConsentRequest) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { res, _, err := apiClient.OAuth2Api.GetOAuth2ConsentRequest(context.Background()).ConsentChallenge(r.URL.Query().Get("consent_challenge")).Execute() payload := cb(t, res, err) v, _, err := apiClient.OAuth2Api.AcceptOAuth2ConsentRequest(context.Background()). ConsentChallenge(r.URL.Query().Get("consent_challenge")). AcceptOAuth2ConsentRequest(payload). Execute() require.NoError(t, err) require.NotEmpty(t, v.RedirectTo) http.Redirect(w, r, v.RedirectTo, http.StatusFound) } } func makeOAuth2Request(t *testing.T, reg driver.Registry, hc *http.Client, oc *client.Client, values url.Values) (gjson.Result, *http.Response) { ctx := context.Background() if hc == nil { hc = testhelpers.NewEmptyJarClient(t) } values.Add("response_type", "code") values.Add("state", uuid.New().String()) values.Add("client_id", oc.GetID()) res, err := hc.Get(urlx.CopyWithQuery(reg.Config().OAuth2AuthURL(ctx), values).String()) require.NoError(t, err) defer res.Body.Close() return gjson.ParseBytes(ioutilx.MustReadAll(res.Body)), res } func createClient(t *testing.T, reg driver.Registry, c *client.Client) *client.Client { secret := uuid.New().String() c.Secret = secret c.Scope = "openid offline" c.LegacyClientID = uuid.New().String() require.NoError(t, reg.ClientManager().CreateClient(context.Background(), c)) c.Secret = secret return c } func newAuthCookieJar(t *testing.T, reg driver.Registry, u, sessionID string) http.CookieJar { ctx := context.Background() cj, err := cookiejar.New(&cookiejar.Options{}) require.NoError(t, err) hr := &http.Request{Header: map[string][]string{}, URL: urlx.ParseOrPanic(u), RequestURI: u} s, err := reg.CookieStore(ctx) require.NoError(t, err) cookie, _ := s.Get(hr, reg.Config().SessionCookieName(ctx)) cookie.Values[CookieAuthenticationSIDName] = sessionID cookie.Options.HttpOnly = true rw := httptest.NewRecorder() require.NoError(t, cookie.Save(hr, rw)) cj.SetCookies(urlx.ParseOrPanic(u), rw.Result().Cookies()) return cj } func genIDToken(t *testing.T, reg driver.Registry, c jwt.MapClaims) string { r, _, err := reg.OpenIDJWTStrategy().Generate(context.Background(), c, jwt.NewHeaders()) require.NoError(t, err) return r } func checkAndDuplicateAcceptLoginHandler(t *testing.T, apiClient *hydra.APIClient, subject string, cb func(*testing.T, *hydra.OAuth2LoginRequest, error) hydra.AcceptOAuth2LoginRequest) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { res, _, err := apiClient.OAuth2Api.GetOAuth2LoginRequest(context.Background()).LoginChallenge(r.URL.Query().Get("login_challenge")).Execute() payload := cb(t, res, err) payload.Subject = subject v, _, err := apiClient.OAuth2Api.AcceptOAuth2LoginRequest(context.Background()). LoginChallenge(r.URL.Query().Get("login_challenge")). AcceptOAuth2LoginRequest(payload). Execute() require.NoError(t, err) require.NotEmpty(t, v.RedirectTo) v2, _, err := apiClient.OAuth2Api.AcceptOAuth2LoginRequest(context.Background()). LoginChallenge(r.URL.Query().Get("login_challenge")). AcceptOAuth2LoginRequest(payload). Execute() require.NoError(t, err) require.NotEmpty(t, v2.RedirectTo) http.Redirect(w, r, v2.RedirectTo, http.StatusFound) } } func checkAndDuplicateAcceptConsentHandler(t *testing.T, apiClient *hydra.APIClient, cb func(*testing.T, *hydra.OAuth2ConsentRequest, error) hydra.AcceptOAuth2ConsentRequest) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { res, _, err := apiClient.OAuth2Api.GetOAuth2ConsentRequest(context.Background()). ConsentChallenge(r.URL.Query().Get("consent_challenge")). Execute() payload := cb(t, res, err) v, _, err := apiClient.OAuth2Api.AcceptOAuth2ConsentRequest(context.Background()). ConsentChallenge(r.URL.Query().Get("consent_challenge")). AcceptOAuth2ConsentRequest(payload). Execute() require.NoError(t, err) require.NotEmpty(t, v.RedirectTo) res2, _, err := apiClient.OAuth2Api.GetOAuth2ConsentRequest(context.Background()).ConsentChallenge(r.URL.Query().Get("consent_challenge")).Execute() payload2 := cb(t, res2, err) v2, _, err := apiClient.OAuth2Api.AcceptOAuth2ConsentRequest(context.Background()). ConsentChallenge(r.URL.Query().Get("consent_challenge")). AcceptOAuth2ConsentRequest(payload2). Execute() require.NoError(t, err) require.NotEmpty(t, v2.RedirectTo) http.Redirect(w, r, v2.RedirectTo, http.StatusFound) } }
Go
hydra/consent/strategy_logout_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent_test import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "strings" "sync" "testing" "time" "github.com/ory/hydra/v2/internal/kratos" "github.com/ory/x/pointerx" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" jwtgo "github.com/ory/fosite/token/jwt" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/internal" "github.com/ory/hydra/v2/internal/testhelpers" "github.com/ory/x/contextx" "github.com/ory/x/ioutilx" ) func TestLogoutFlows(t *testing.T) { ctx := context.Background() fakeKratos := kratos.NewFake() reg := internal.NewMockedRegistry(t, &contextx.Default{}) reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque") reg.Config().MustSet(ctx, config.KeyConsentRequestMaxAge, time.Hour) reg.WithKratos(fakeKratos) defaultRedirectedMessage := "redirected to default server" postLogoutCallback := func(w http.ResponseWriter, r *http.Request) { _ = r.ParseForm() _, _ = fmt.Fprintf(w, "%s%s%s", defaultRedirectedMessage, r.Form.Get("state"), strings.TrimLeft(r.URL.Path, "/")) } defaultLogoutURL := testhelpers.NewCallbackURL(t, "logged-out", postLogoutCallback) customPostLogoutURL := testhelpers.NewCallbackURL(t, "logged-out/custom", postLogoutCallback) reg.Config().MustSet(ctx, config.KeyLogoutRedirectURL, defaultLogoutURL) publicTS, adminTS := testhelpers.NewOAuth2Server(ctx, t, reg) adminApi := hydra.NewAPIClient(hydra.NewConfiguration()) adminApi.GetConfig().Servers = hydra.ServerConfigurations{{URL: adminTS.URL}} createBrowserWithSession := func(t *testing.T, c *client.Client) *http.Client { hc := testhelpers.NewEmptyJarClient(t) makeOAuth2Request(t, reg, hc, c, url.Values{}) return hc } createSampleClient := func(t *testing.T) *client.Client { return createClient(t, reg, &client.Client{ RedirectURIs: []string{testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)}, PostLogoutRedirectURIs: []string{customPostLogoutURL}}) } createClientWithBackchannelLogout := func(t *testing.T, wg *sync.WaitGroup, cb func(t *testing.T, logoutToken gjson.Result)) *client.Client { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer wg.Done() require.NoError(t, r.ParseForm()) lt := r.PostFormValue("logout_token") assert.NotEmpty(t, lt) token, err := reg.OpenIDJWTStrategy().Decode(r.Context(), lt) require.NoError(t, err) var b bytes.Buffer require.NoError(t, json.NewEncoder(&b).Encode(token.Claims)) cb(t, gjson.Parse(b.String())) })) t.Cleanup(server.Close) return createClient(t, reg, &client.Client{ BackChannelLogoutURI: server.URL, RedirectURIs: []string{testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)}, PostLogoutRedirectURIs: []string{customPostLogoutURL}}) } makeLogoutRequest := func(t *testing.T, hc *http.Client, method string, values url.Values) (body string, resp *http.Response) { var err error if method == http.MethodGet { resp, err = hc.Get(publicTS.URL + "/oauth2/sessions/logout?" + values.Encode()) } else if method == http.MethodPost { resp, err = hc.PostForm(publicTS.URL+"/oauth2/sessions/logout", values) } require.NoError(t, err) defer resp.Body.Close() return string(ioutilx.MustReadAll(resp.Body)), resp } makeHeadlessLogoutRequest := func(t *testing.T, hc *http.Client, values url.Values) (body string, resp *http.Response) { var err error req, err := http.NewRequest(http.MethodDelete, adminTS.URL+"/admin/oauth2/auth/sessions/login?"+values.Encode(), nil) require.NoError(t, err) resp, err = hc.Do(req) require.NoError(t, err) defer resp.Body.Close() return string(ioutilx.MustReadAll(resp.Body)), resp } logoutViaHeadlessAndExpectNoContent := func(t *testing.T, browser *http.Client, values url.Values) { _, res := makeHeadlessLogoutRequest(t, browser, values) assert.EqualValues(t, http.StatusNoContent, res.StatusCode) } logoutViaHeadlessAndExpectError := func(t *testing.T, browser *http.Client, values url.Values, expectedErrorMessage string) { body, res := makeHeadlessLogoutRequest(t, browser, values) assert.EqualValues(t, http.StatusBadRequest, res.StatusCode) assert.Contains(t, body, expectedErrorMessage) } logoutAndExpectErrorPage := func(t *testing.T, browser *http.Client, method string, values url.Values, expectedErrorMessage string) { body, res := makeLogoutRequest(t, browser, method, values) assert.EqualValues(t, http.StatusInternalServerError, res.StatusCode) assert.Contains(t, body, expectedErrorMessage) } testExpectErrorPage := func(browser *http.Client, method string, values url.Values, expectedErrorMessage string) func(t *testing.T) { return func(t *testing.T) { logoutAndExpectErrorPage(t, browser, method, values, expectedErrorMessage) } } logoutAndExpectPostLogoutPage := func(t *testing.T, browser *http.Client, method string, values url.Values, expectedMessage string) { body, res := makeLogoutRequest(t, browser, method, values) assert.EqualValues(t, http.StatusOK, res.StatusCode) assert.Contains(t, body, expectedMessage) } testExpectPostLogoutPage := func(browser *http.Client, method string, values url.Values, expectedMessage string) func(t *testing.T) { return func(t *testing.T) { logoutAndExpectPostLogoutPage(t, browser, method, values, expectedMessage) } } browserWithoutSession := new(http.Client) newWg := func(add int) *sync.WaitGroup { var wg sync.WaitGroup wg.Add(add) return &wg } checkAndAcceptLogout := func(t *testing.T, wg *sync.WaitGroup, cb func(*testing.T, *hydra.OAuth2LogoutRequest, error)) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if wg != nil { defer wg.Done() } res, _, err := adminApi.OAuth2Api.GetOAuth2LogoutRequest(ctx).LogoutChallenge(r.URL.Query().Get("logout_challenge")).Execute() if cb != nil { cb(t, res, err) } v, _, err := adminApi.OAuth2Api.AcceptOAuth2LogoutRequest(ctx).LogoutChallenge(r.URL.Query().Get("logout_challenge")).Execute() require.NoError(t, err) require.NotEmpty(t, v.RedirectTo) http.Redirect(w, r, v.RedirectTo, http.StatusFound) })) t.Cleanup(server.Close) reg.Config().MustSet(ctx, config.KeyLogoutURL, server.URL) } acceptLoginAsAndWatchSidForConsumers := func(t *testing.T, subject string, sid chan string, remember bool, numSidConsumers int) { testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminApi, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) //res.Payload.SessionID return hydra.AcceptOAuth2LoginRequest{ Remember: pointerx.Ptr(true), IdentityProviderSessionId: pointerx.Ptr(kratos.FakeSessionID), } }), checkAndAcceptConsentHandler(t, adminApi, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) if sid != nil { go func() { for i := 0; i < numSidConsumers; i++ { sid <- *res.LoginSessionId } }() } return hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(remember)} })) } acceptLoginAsAndWatchSid := func(t *testing.T, subject string, sid chan string) { acceptLoginAsAndWatchSidForConsumers(t, subject, sid, true, 1) } acceptLoginAs := func(t *testing.T, subject string) { acceptLoginAsAndWatchSidForConsumers(t, subject, nil, true, 0) } subject := "aeneas-rekkas" t.Run("case=should ignore / redirect non-rp initiated logout if no session exists", func(t *testing.T) { t.Run("method=get", testExpectPostLogoutPage(browserWithoutSession, http.MethodGet, url.Values{}, defaultRedirectedMessage)) t.Run("method=post", testExpectPostLogoutPage(browserWithoutSession, http.MethodPost, url.Values{}, defaultRedirectedMessage)) }) t.Run("case=should fail if non-rp initiated logout is initiated with state (indicating rp-flow)", func(t *testing.T) { expectedMessage := "Logout failed because query parameter state is set but id_token_hint is missing" values := url.Values{"state": {"foobar"}} t.Run("method=get", testExpectErrorPage(browserWithoutSession, http.MethodGet, values, expectedMessage)) t.Run("method=post", testExpectErrorPage(browserWithoutSession, http.MethodPost, values, expectedMessage)) }) t.Run("case=should fail if non-rp initiated logout is initiated with post_logout_redirect_uri (indicating rp-flow)", func(t *testing.T) { expectedMessage := "Logout failed because query parameter post_logout_redirect_uri is set but id_token_hint is missing" values := url.Values{"post_logout_redirect_uri": {"foobar"}} t.Run("method=get", testExpectErrorPage(browserWithoutSession, http.MethodGet, values, expectedMessage)) t.Run("method=post", testExpectErrorPage(browserWithoutSession, http.MethodPost, values, expectedMessage)) }) t.Run("case=should ignore / redirect non-rp initiated logout if a session cookie exists but the session itself is no longer active / invalid", func(t *testing.T) { browser := &http.Client{Jar: newAuthCookieJar(t, reg, publicTS.URL, "i-do-not-exist")} t.Run("method=get", testExpectPostLogoutPage(browser, http.MethodGet, url.Values{}, defaultRedirectedMessage)) t.Run("method=post", testExpectPostLogoutPage(browser, http.MethodPost, url.Values{}, defaultRedirectedMessage)) }) t.Run("case=should redirect to logout provider if session exists and it's not rp-flow", func(t *testing.T) { acceptLoginAs(t, subject) wg := newWg(2) checkAndAcceptLogout(t, wg, func(t *testing.T, res *hydra.OAuth2LogoutRequest, err error) { require.NoError(t, err) assert.EqualValues(t, subject, *res.Subject) assert.NotEmpty(t, subject, res.Sid) }) t.Run("method=get", testExpectPostLogoutPage(createBrowserWithSession(t, createSampleClient(t)), http.MethodGet, url.Values{}, defaultRedirectedMessage)) t.Run("method=post", testExpectPostLogoutPage(createBrowserWithSession(t, createSampleClient(t)), http.MethodPost, url.Values{}, defaultRedirectedMessage)) wg.Wait() // we want to ensure that logout ui was called! }) t.Run("case=should redirect to post logout url because logout was already done before", func(t *testing.T) { // Formerly: should redirect to logout provider because the session has been removed previously acceptLoginAs(t, subject) browser := createBrowserWithSession(t, createSampleClient(t)) // run once to invalidate session wg := newWg(1) checkAndAcceptLogout(t, wg, nil) logoutAndExpectPostLogoutPage(t, browser, http.MethodGet, url.Values{}, defaultRedirectedMessage) t.Run("method=get", testExpectPostLogoutPage(browser, http.MethodGet, url.Values{}, defaultRedirectedMessage)) t.Run("method=post", testExpectPostLogoutPage(browser, http.MethodPost, url.Values{}, defaultRedirectedMessage)) wg.Wait() // we want to ensure that logout ui was called exactly once }) t.Run("case=should execute backchannel logout if issued without rp-involvement", func(t *testing.T) { sid := make(chan string) acceptLoginAsAndWatchSid(t, subject, sid) logoutWg := newWg(2) checkAndAcceptLogout(t, logoutWg, nil) backChannelWG := newWg(2) c := createClientWithBackchannelLogout(t, backChannelWG, func(t *testing.T, logoutToken gjson.Result) { assert.EqualValues(t, <-sid, logoutToken.Get("sid").String(), logoutToken.Raw) assert.Empty(t, logoutToken.Get("sub").String(), logoutToken.Raw) // The sub claim should be empty because it doesn't work with forced obfuscation and thus we can't easily recover it. assert.Empty(t, logoutToken.Get("nonce").String(), logoutToken.Raw) }) t.Run("method=get", testExpectPostLogoutPage(createBrowserWithSession(t, c), http.MethodGet, url.Values{}, defaultRedirectedMessage)) t.Run("method=post", testExpectPostLogoutPage(createBrowserWithSession(t, c), http.MethodPost, url.Values{}, defaultRedirectedMessage)) logoutWg.Wait() // we want to ensure that logout ui was called! backChannelWG.Wait() // we want to ensure that all back channels have been called! }) // Only do GET requests from here on out, POST should be tested enough to ensure that it is working fine already. t.Run("case=should fail several flows when id_token_hint is invalid", func(t *testing.T) { t.Run("case=should error when rp-flow without valid id token", func(t *testing.T) { acceptLoginAs(t, "aeneas-rekkas") checkAndAcceptLogout(t, nil, nil) expectedMessage := "compact JWS format must have three parts" browser := createBrowserWithSession(t, createSampleClient(t)) values := url.Values{"state": {"1234"}, "post_logout_redirect_uri": {customPostLogoutURL}, "id_token_hint": {"i am not valid"}} t.Run("method=get", testExpectErrorPage(browser, http.MethodGet, values, expectedMessage)) t.Run("method=post", testExpectErrorPage(browser, http.MethodPost, values, expectedMessage)) }) for _, tc := range []struct { d string claims jwtgo.MapClaims expectedErrMessage string }{ { d: "should fail rp-inititated flow because id token hint is missing issuer", claims: jwtgo.MapClaims{ "iat": time.Now().Add(-time.Hour * 2).Unix(), }, expectedErrMessage: "Logout failed because issuer claim value &#39;&#39; from query parameter id_token_hint does not match with issuer value from configuration", }, { d: "should fail rp-inititated flow because id token hint is using wrong issuer", claims: jwtgo.MapClaims{ "iss": "some-issuer", "iat": time.Now().Add(-time.Hour * 2).Unix(), }, expectedErrMessage: "Logout failed because issuer claim value &#39;some-issuer&#39; from query parameter id_token_hint does not match with issuer value from configuration", }, { d: "should fail rp-inititated flow because iat is in the future", claims: jwtgo.MapClaims{ "iss": reg.Config().IssuerURL(ctx).String(), "iat": time.Now().Add(time.Hour * 2).Unix(), }, expectedErrMessage: "Token used before issued", }, } { t.Run("case="+tc.d, func(t *testing.T) { c := createSampleClient(t) sid := make(chan string) acceptLoginAsAndWatchSid(t, subject, sid) browser := createBrowserWithSession(t, c) wg := newWg(1) checkAndAcceptLogout(t, wg, nil) tc.claims["sub"] = subject tc.claims["sid"] = <-sid tc.claims["aud"] = c.GetID() tc.claims["exp"] = time.Now().Add(-time.Hour).Unix() logoutAndExpectErrorPage(t, browser, http.MethodGet, url.Values{ "state": {"1234"}, "post_logout_redirect_uri": {customPostLogoutURL}, "id_token_hint": {testhelpers.NewIDTokenWithClaims(t, reg, tc.claims)}, }, tc.expectedErrMessage) wg.Done() }) } }) t.Run("case=should fail because post-logout url is not registered", func(t *testing.T) { c := createSampleClient(t) acceptLoginAs(t, subject) browser := createBrowserWithSession(t, c) values := url.Values{ "state": {"1234"}, "post_logout_redirect_uri": {"https://this-is-not-a-valid-redirect-url/custom"}, "id_token_hint": {testhelpers.NewIDTokenWithClaims(t, reg, jwtgo.MapClaims{ "aud": c.GetID(), "iss": reg.Config().IssuerURL(ctx).String(), "sub": subject, "sid": "logout-session-temp4", "exp": time.Now().Add(-time.Hour).Unix(), "iat": time.Now().Add(-time.Hour * 2).Unix(), })}, } logoutAndExpectErrorPage(t, browser, http.MethodGet, values, "Logout failed because query parameter post_logout_redirect_uri is not a whitelisted as a post_logout_redirect_uri for the client") }) t.Run("case=should pass rp-initiated flows", func(t *testing.T) { c := createSampleClient(t) run := func(method string, claims jwtgo.MapClaims) func(t *testing.T) { return func(t *testing.T) { sid := make(chan string) acceptLoginAsAndWatchSid(t, subject, sid) checkAndAcceptLogout(t, nil, nil) browser := createBrowserWithSession(t, c) sendClaims := jwtgo.MapClaims{ "iss": reg.Config().IssuerURL(ctx).String(), "aud": c.GetID(), "sid": <-sid, "sub": subject, "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Add(-time.Hour).Unix(), } for k, v := range claims { sendClaims[k] = v } body, res := makeLogoutRequest(t, browser, method, url.Values{ "state": {"1234"}, "post_logout_redirect_uri": {customPostLogoutURL}, "id_token_hint": {testhelpers.NewIDTokenWithClaims(t, reg, sendClaims)}, }) assert.EqualValues(t, http.StatusOK, res.StatusCode) assert.Contains(t, body, "redirected to default server1234logged-out/custom") assert.Contains(t, res.Request.URL.String(), "/logged-out/custom?state=1234") } } t.Run("case=should pass even if expiry is in the past", func(t *testing.T) { // formerly: should pass rp-inititated even when expiry is in the past claims := jwtgo.MapClaims{"exp": time.Now().Add(-time.Hour).Unix()} t.Run("method=GET", run("GET", claims)) t.Run("method=POST", run("POST", claims)) }) t.Run("case=should pass even if audience is an array not a string", func(t *testing.T) { // formerly: should pass rp-inititated flow" claims := jwtgo.MapClaims{"aud": []string{c.GetID()}} t.Run("method=GET", run("GET", claims)) t.Run("method=POST", run("POST", claims)) }) }) t.Run("case=should pass rp-inititated flow without any action because SID is unknown", func(t *testing.T) { c := createSampleClient(t) acceptLoginAs(t, subject) checkAndAcceptLogout(t, nil, func(t *testing.T, res *hydra.OAuth2LogoutRequest, err error) { t.Fatalf("Logout should not have been called") }) browser := createBrowserWithSession(t, c) logoutAndExpectPostLogoutPage(t, browser, "GET", url.Values{ "state": {"1234"}, "post_logout_redirect_uri": {customPostLogoutURL}, "id_token_hint": {genIDToken(t, reg, jwtgo.MapClaims{ "aud": []string{c.GetID()}, // make sure this works with string slices too "iss": reg.Config().IssuerURL(ctx).String(), "sub": subject, "sid": "i-do-not-exist", "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Add(-time.Hour).Unix(), })}, }, defaultRedirectedMessage+"1234logged-out/custom") }) t.Run("case=should not append a state param if no state was passed to logout server", func(t *testing.T) { c := createSampleClient(t) sid := make(chan string) acceptLoginAsAndWatchSid(t, subject, sid) checkAndAcceptLogout(t, nil, nil) browser := createBrowserWithSession(t, c) body, res := makeLogoutRequest(t, browser, "GET", url.Values{ "post_logout_redirect_uri": {customPostLogoutURL}, "id_token_hint": {testhelpers.NewIDTokenWithClaims(t, reg, jwtgo.MapClaims{ "iss": reg.Config().IssuerURL(ctx).String(), "aud": c.GetID(), "sid": <-sid, "sub": subject, "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Add(-time.Hour).Unix(), })}, }) assert.EqualValues(t, http.StatusOK, res.StatusCode) assert.Contains(t, body, "redirected to default serverlogged-out/custom") assert.Contains(t, res.Request.URL.String(), "/logged-out/custom") assert.NotContains(t, res.Request.URL.String(), "state=1234") }) t.Run("case=should return to default post logout because session was revoked in browser context", func(t *testing.T) { fakeKratos.Reset() c := createSampleClient(t) sid := make(chan string) acceptLoginAsAndWatchSid(t, subject, sid) wg := newWg(2) checkAndAcceptLogout(t, wg, nil) browser := createBrowserWithSession(t, c) // Use another browser (without session cookie) to make the logout request: otherBrowser := &http.Client{} logoutAndExpectPostLogoutPage(t, otherBrowser, "GET", url.Values{ "post_logout_redirect_uri": {customPostLogoutURL}, "id_token_hint": {testhelpers.NewIDTokenWithClaims(t, reg, jwtgo.MapClaims{ "iss": reg.Config().IssuerURL(ctx).String(), "aud": c.GetID(), "sid": <-sid, "sub": subject, "exp": time.Now().Add(time.Hour).Unix(), "iat": time.Now().Add(-time.Hour).Unix(), })}, }, "redirected to default serverlogged-out/custom") // this means RP-initiated flow worked! // Set up login / consent and check if skip is set to false (because logout happened), but use // the original login browser which still has the session. testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminApi, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { defer wg.Done() require.NoError(t, err) assert.False(t, res.Skip) return hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)} }), checkAndAcceptConsentHandler(t, adminApi, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) return hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)} })) // Make an oauth 2 request to trigger the login check. _, res := makeOAuth2Request(t, reg, browser, c, url.Values{}) assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode) assert.NotEmpty(t, res.Request.URL.Query().Get("code")) wg.Wait() assert.True(t, fakeKratos.DisableSessionWasCalled) assert.Equal(t, fakeKratos.LastDisabledSession, kratos.FakeSessionID) }) t.Run("case=should execute backchannel logout in headless flow with sid", func(t *testing.T) { fakeKratos.Reset() numSidConsumers := 2 sid := make(chan string, numSidConsumers) acceptLoginAsAndWatchSidForConsumers(t, subject, sid, true, numSidConsumers) backChannelWG := newWg(1) c := createClientWithBackchannelLogout(t, backChannelWG, func(t *testing.T, logoutToken gjson.Result) { assert.EqualValues(t, <-sid, logoutToken.Get("sid").String(), logoutToken.Raw) assert.Empty(t, logoutToken.Get("sub").String(), logoutToken.Raw) // The sub claim should be empty because it doesn't work with forced obfuscation and thus we can't easily recover it. assert.Empty(t, logoutToken.Get("nonce").String(), logoutToken.Raw) }) logoutViaHeadlessAndExpectNoContent(t, createBrowserWithSession(t, c), url.Values{"sid": {<-sid}}) backChannelWG.Wait() // we want to ensure that all back channels have been called! assert.True(t, fakeKratos.DisableSessionWasCalled) assert.Equal(t, fakeKratos.LastDisabledSession, kratos.FakeSessionID) }) t.Run("case=should logout in headless flow with non-existing sid", func(t *testing.T) { fakeKratos.Reset() logoutViaHeadlessAndExpectNoContent(t, browserWithoutSession, url.Values{"sid": {"non-existing-sid"}}) assert.False(t, fakeKratos.DisableSessionWasCalled) }) t.Run("case=should logout in headless flow with session that has remember=false", func(t *testing.T) { fakeKratos.Reset() sid := make(chan string) acceptLoginAsAndWatchSidForConsumers(t, subject, sid, false, 1) c := createSampleClient(t) logoutViaHeadlessAndExpectNoContent(t, createBrowserWithSession(t, c), url.Values{"sid": {<-sid}}) assert.True(t, fakeKratos.DisableSessionWasCalled) assert.Equal(t, fakeKratos.LastDisabledSession, kratos.FakeSessionID) }) t.Run("case=should fail headless logout because neither sid nor subject were provided", func(t *testing.T) { fakeKratos.Reset() logoutViaHeadlessAndExpectError(t, browserWithoutSession, url.Values{}, `Either 'subject' or 'sid' query parameters need to be defined.`) assert.False(t, fakeKratos.DisableSessionWasCalled) }) }
Go
hydra/consent/strategy_oauth_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent_test import ( "bytes" "context" "crypto/sha256" "encoding/json" "fmt" "net/http" "net/http/cookiejar" "net/url" "regexp" "testing" "time" "github.com/ory/hydra/v2/aead" "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/flow" "github.com/ory/hydra/v2/oauth2/flowctx" "github.com/ory/hydra/v2/x" "github.com/ory/x/ioutilx" "golang.org/x/exp/slices" "golang.org/x/oauth2" "github.com/ory/x/pointerx" "github.com/tidwall/gjson" "github.com/pborman/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ory/hydra/v2/internal/testhelpers" "github.com/ory/x/contextx" "github.com/ory/fosite" "github.com/ory/x/urlx" "github.com/ory/x/uuidx" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/internal" ) func TestStrategyLoginConsentNext(t *testing.T) { ctx := context.Background() reg := internal.NewMockedRegistry(t, &contextx.Default{}) reg.Config().MustSet(ctx, config.KeyAccessTokenStrategy, "opaque") reg.Config().MustSet(ctx, config.KeyConsentRequestMaxAge, time.Hour) reg.Config().MustSet(ctx, config.KeyConsentRequestMaxAge, time.Hour) reg.Config().MustSet(ctx, config.KeyScopeStrategy, "exact") reg.Config().MustSet(ctx, config.KeySubjectTypesSupported, []string{"pairwise", "public"}) reg.Config().MustSet(ctx, config.KeySubjectIdentifierAlgorithmSalt, "76d5d2bf-747f-4592-9fbd-d2b895a54b3a") publicTS, adminTS := testhelpers.NewOAuth2Server(ctx, t, reg) adminClient := hydra.NewAPIClient(hydra.NewConfiguration()) adminClient.GetConfig().Servers = hydra.ServerConfigurations{{URL: adminTS.URL}} oauth2Config := func(t *testing.T, c *client.Client) *oauth2.Config { return &oauth2.Config{ ClientID: c.GetID(), ClientSecret: c.Secret, Endpoint: oauth2.Endpoint{ AuthURL: publicTS.URL + "/oauth2/auth", TokenURL: publicTS.URL + "/oauth2/token", AuthStyle: oauth2.AuthStyleInHeader, }, RedirectURL: c.RedirectURIs[0], } } acceptLoginHandler := func(t *testing.T, subject string, payload *hydra.AcceptOAuth2LoginRequest) http.HandlerFunc { return checkAndAcceptLoginHandler(t, adminClient, subject, func(*testing.T, *hydra.OAuth2LoginRequest, error) hydra.AcceptOAuth2LoginRequest { if payload == nil { return hydra.AcceptOAuth2LoginRequest{} } return *payload }) } acceptConsentHandler := func(t *testing.T, payload *hydra.AcceptOAuth2ConsentRequest) http.HandlerFunc { return checkAndAcceptConsentHandler(t, adminClient, func(*testing.T, *hydra.OAuth2ConsentRequest, error) hydra.AcceptOAuth2ConsentRequest { if payload == nil { return hydra.AcceptOAuth2ConsentRequest{} } return *payload }) } createClientWithRedir := func(t *testing.T, redir string) *client.Client { c := &client.Client{RedirectURIs: []string{redir}} return createClient(t, reg, c) } createDefaultClient := func(t *testing.T) *client.Client { return createClientWithRedir(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)) } makeRequestAndExpectCode := func(t *testing.T, hc *http.Client, c *client.Client, values url.Values) string { _, res := makeOAuth2Request(t, reg, hc, c, values) assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode) code := res.Request.URL.Query().Get("code") assert.NotEmpty(t, code) return code } makeRequestAndExpectError := func(t *testing.T, hc *http.Client, c *client.Client, values url.Values, errContains string) { _, res := makeOAuth2Request(t, reg, hc, c, values) assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode) assert.Empty(t, res.Request.URL.Query().Get("code")) assert.Contains(t, res.Request.URL.Query().Get("error_description"), errContains, "%v", res.Request.URL.Query()) } t.Run("case=should fail because a login verifier was given that doesn't exist in the store", func(t *testing.T) { testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNoExpectedCallHandler(t), testhelpers.HTTPServerNoExpectedCallHandler(t)) c := createDefaultClient(t) hc := newHTTPClientWithFlowCookie(t, ctx, reg, c) makeRequestAndExpectError( t, hc, c, url.Values{"login_verifier": {"does-not-exist"}}, "The login verifier has already been used, has not been granted, or is invalid.", ) }) t.Run("case=should fail because a non-existing consent verifier was given", func(t *testing.T) { // Covers: // - This should fail because consent verifier was set but does not exist // - This should fail because a consent verifier was given but no login verifier testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNoExpectedCallHandler(t), testhelpers.HTTPServerNoExpectedCallHandler(t)) c := createDefaultClient(t) hc := newHTTPClientWithFlowCookie(t, ctx, reg, c) makeRequestAndExpectError( t, hc, c, url.Values{"consent_verifier": {"does-not-exist"}}, "The consent verifier has already been used, has not been granted, or is invalid.", ) }) t.Run("case=should fail because the request was redirected but the login endpoint doesn't do anything (like redirecting back)", func(t *testing.T) { testhelpers.NewLoginConsentUI(t, reg.Config(), testhelpers.HTTPServerNotImplementedHandler, testhelpers.HTTPServerNoExpectedCallHandler(t)) c := createClientWithRedir(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNoExpectedCallHandler(t))) _, res := makeOAuth2Request(t, reg, nil, c, url.Values{}) assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode) assert.NotEmpty(t, res.Request.URL.Query().Get("login_challenge"), "%s", res.Request.URL) }) t.Run("case=should fail because the request was redirected but consent endpoint doesn't do anything (like redirecting back)", func(t *testing.T) { // "This should fail because consent endpoints idles after login was granted - but consent endpoint should be called because cookie jar exists" testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", nil), testhelpers.HTTPServerNotImplementedHandler) c := createClientWithRedir(t, testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNoExpectedCallHandler(t))) _, res := makeOAuth2Request(t, reg, nil, c, url.Values{}) assert.EqualValues(t, http.StatusNotImplemented, res.StatusCode) assert.NotEmpty(t, res.Request.URL.Query().Get("consent_challenge"), "%s", res.Request.URL) }) t.Run("case=should fail because the request was redirected but the login endpoint rejected the request", func(t *testing.T) { testhelpers.NewLoginConsentUI(t, reg.Config(), func(w http.ResponseWriter, r *http.Request) { vr, _, err := adminClient.OAuth2Api.RejectOAuth2LoginRequest(context.Background()). LoginChallenge(r.URL.Query().Get("login_challenge")). RejectOAuth2Request(hydra.RejectOAuth2Request{ Error: pointerx.String(fosite.ErrInteractionRequired.ErrorField), ErrorDescription: pointerx.String("expect-reject-login"), StatusCode: pointerx.Int64(int64(fosite.ErrInteractionRequired.CodeField)), }).Execute() require.NoError(t, err) assert.NotEmpty(t, vr.RedirectTo) http.Redirect(w, r, vr.RedirectTo, http.StatusFound) }, testhelpers.HTTPServerNoExpectedCallHandler(t)) c := createDefaultClient(t) makeRequestAndExpectError(t, nil, c, url.Values{}, "expect-reject-login") }) t.Run("case=should fail because no cookie jar invalid csrf", func(t *testing.T) { c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", nil), testhelpers.HTTPServerNoExpectedCallHandler(t)) hc := new(http.Client) hc.Jar = DropCookieJar(regexp.MustCompile("ory_hydra_.*_csrf_.*")) makeRequestAndExpectError(t, hc, c, url.Values{}, "No CSRF value available in the session cookie.") }) t.Run("case=should fail because consent endpoints denies the request after login was granted", func(t *testing.T) { c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", nil), func(w http.ResponseWriter, r *http.Request) { vr, _, err := adminClient.OAuth2Api.RejectOAuth2ConsentRequest(context.Background()). ConsentChallenge(r.URL.Query().Get("consent_challenge")). RejectOAuth2Request(hydra.RejectOAuth2Request{ Error: pointerx.String(fosite.ErrInteractionRequired.ErrorField), ErrorDescription: pointerx.String("expect-reject-consent"), StatusCode: pointerx.Int64(int64(fosite.ErrInteractionRequired.CodeField))}).Execute() require.NoError(t, err) require.NotEmpty(t, vr.RedirectTo) http.Redirect(w, r, vr.RedirectTo, http.StatusFound) }) makeRequestAndExpectError(t, nil, c, url.Values{}, "expect-reject-consent") }) t.Run("case=should pass and set acr values properly", func(t *testing.T) { c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", nil), acceptConsentHandler(t, nil)) makeRequestAndExpectCode(t, nil, c, url.Values{}) }) t.Run("case=should pass if both login and consent are granted and check remember flows as well as various payloads", func(t *testing.T) { // Covers old test cases: // - This should pass because login and consent have been granted, this time we remember the decision // - This should pass because login and consent have been granted, this time we remember the decision#2 // - This should pass because login and consent have been granted, this time we remember the decision#3 // - This should pass because login was remembered and session id should be set and session context should also work // - This should pass and confirm previous authentication and consent because it is a authorization_code subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ Remember: pointerx.Bool(true), }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, })) hc := testhelpers.NewEmptyJarClient(t) conf := oauth2Config(t, c) var sid string var run = func(t *testing.T) { code := makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}}) token, err := conf.Exchange(context.Background(), code) require.NoError(t, err) claims := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS) assert.Equal(t, "bar", claims.Get("ext.foo").String(), "%s", claims.Raw) idClaims := testhelpers.DecodeIDToken(t, token) assert.Equal(t, "baz", idClaims.Get("bar").String(), "%s", idClaims.Raw) sid = idClaims.Get("sid").String() assert.NotNil(t, sid) } t.Run("perform first flow", run) t.Run("perform follow up flows and check if session values are set", func(t *testing.T) { testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) assert.True(t, res.Skip) assert.Equal(t, sid, *res.SessionId) assert.Equal(t, subject, res.Subject) assert.Empty(t, pointerx.StringR(res.Client.ClientSecret)) return hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"foo": "bar"}, } }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.True(t, *res.Skip) assert.Equal(t, sid, *res.LoginSessionId) assert.Equal(t, subject, *res.Subject) assert.Empty(t, pointerx.StringR(res.Client.ClientSecret)) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) for k := 0; k < 3; k++ { t.Run(fmt.Sprintf("case=%d", k), run) } }) }) t.Run("case=should set client specific csrf cookie names", func(t *testing.T) { subject := "subject-1" consentRequestMaxAge := reg.Config().ConsentRequestMaxAge(ctx).Seconds() c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ Remember: pointerx.Bool(true), }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, })) testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) assert.Empty(t, res.Subject) assert.Empty(t, pointerx.StringR(res.Client.ClientSecret)) return hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"foo": "bar"}, } }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.Equal(t, subject, *res.Subject) assert.Empty(t, pointerx.StringR(res.Client.ClientSecret)) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := &http.Client{ Jar: testhelpers.NewEmptyCookieJar(t), Transport: &http.Transport{}, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } _, oauthRes := makeOAuth2Request(t, reg, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}}) assert.EqualValues(t, http.StatusFound, oauthRes.StatusCode) loginChallengeRedirect, err := oauthRes.Location() require.NoError(t, err) defer oauthRes.Body.Close() foundLoginCookie := slices.ContainsFunc(oauthRes.Header.Values("set-cookie"), func(sc string) bool { ok, err := regexp.MatchString(fmt.Sprintf("ory_hydra_login_csrf_dev_%s=.*Max-Age=%.0f;.*", c.CookieSuffix(), consentRequestMaxAge), sc) require.NoError(t, err) return ok }) require.True(t, foundLoginCookie, "client-specific login cookie with max age set") loginChallengeRes, err := hc.Get(loginChallengeRedirect.String()) require.NoError(t, err) defer loginChallengeRes.Body.Close() loginVerifierRedirect, err := loginChallengeRes.Location() require.NoError(t, err) loginVerifierRes, err := hc.Get(loginVerifierRedirect.String()) require.NoError(t, err) defer loginVerifierRes.Body.Close() foundConsentCookie := slices.ContainsFunc(loginVerifierRes.Header.Values("set-cookie"), func(sc string) bool { ok, err := regexp.MatchString(fmt.Sprintf("ory_hydra_consent_csrf_dev_%s=.*Max-Age=%.0f;.*", c.CookieSuffix(), consentRequestMaxAge), sc) require.NoError(t, err) return ok }) require.True(t, foundConsentCookie, "client-specific consent cookie with max age set") }) t.Run("case=should pass if both login and consent are granted and check remember flows with refresh session cookie", func(t *testing.T) { subject := "subject-1" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ Remember: pointerx.Bool(true), }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, })) hc := testhelpers.NewEmptyJarClient(t) followUpHandler := func(extendSessionLifespan bool) { rememberFor := int64(12345) testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) assert.True(t, res.Skip) assert.Equal(t, subject, res.Subject) assert.Empty(t, res.Client.ClientSecret) return hydra.AcceptOAuth2LoginRequest{ Subject: subject, Remember: pointerx.Bool(true), RememberFor: pointerx.Int64(rememberFor), ExtendSessionLifespan: pointerx.Bool(extendSessionLifespan), Context: map[string]interface{}{"foo": "bar"}, } }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.True(t, *res.Skip) assert.Equal(t, subject, res.Subject) assert.Empty(t, res.Client.ClientSecret) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := &http.Client{ Jar: hc.Jar, Transport: &http.Transport{}, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } _, oauthRes := makeOAuth2Request(t, reg, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}}) assert.EqualValues(t, http.StatusFound, oauthRes.StatusCode) loginChallengeRedirect, err := oauthRes.Location() require.NoError(t, err) defer oauthRes.Body.Close() loginChallengeRes, err := hc.Get(loginChallengeRedirect.String()) require.NoError(t, err) defer loginChallengeRes.Body.Close() loginVerifierRedirect, err := loginChallengeRes.Location() require.NoError(t, err) loginVerifierRes, err := hc.Get(loginVerifierRedirect.String()) require.NoError(t, err) defer loginVerifierRes.Body.Close() setCookieHeader := loginVerifierRes.Header.Get("set-cookie") assert.NotNil(t, setCookieHeader) if extendSessionLifespan { assert.Regexp(t, fmt.Sprintf("ory_hydra_session_dev=.*; Path=/; Expires=.*Max-Age=%d; HttpOnly; SameSite=Lax", rememberFor), setCookieHeader) } else { assert.NotContains(t, setCookieHeader, "ory_hydra_session_dev") } } t.Run("perform first flow", func(t *testing.T) { makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}}) }) t.Run("perform follow up flow with extend_session_lifespan=false", func(t *testing.T) { followUpHandler(false) }) t.Run("perform follow up flow with extend_session_lifespan=true", func(t *testing.T) { followUpHandler(true) }) }) t.Run("case=should set session cookie with correct configuration", func(t *testing.T) { cookiePath := "/foo" reg.Config().MustSet(ctx, config.KeyCookieSessionPath, cookiePath) defer reg.Config().MustSet(ctx, config.KeyCookieSessionPath, "/") subject := "subject-1" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ Remember: pointerx.Bool(true), }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, })) testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) assert.Empty(t, res.Subject) assert.Empty(t, pointerx.StringR(res.Client.ClientSecret)) return hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"foo": "bar"}, } }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.Equal(t, subject, *res.Subject) assert.Empty(t, pointerx.StringR(res.Client.ClientSecret)) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := &http.Client{ Jar: testhelpers.NewEmptyCookieJar(t), Transport: &http.Transport{}, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } _, oauthRes := makeOAuth2Request(t, reg, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "scope": {"openid"}}) assert.EqualValues(t, http.StatusFound, oauthRes.StatusCode) loginChallengeRedirect, err := oauthRes.Location() require.NoError(t, err) defer oauthRes.Body.Close() loginChallengeRes, err := hc.Get(loginChallengeRedirect.String()) require.NoError(t, err) defer loginChallengeRes.Body.Close() loginVerifierRedirect, err := loginChallengeRes.Location() require.NoError(t, err) loginVerifierRes, err := hc.Get(loginVerifierRedirect.String()) require.NoError(t, err) defer loginVerifierRes.Body.Close() setCookieHeader := loginVerifierRes.Header.Get("set-cookie") assert.NotNil(t, setCookieHeader) assert.Regexp(t, fmt.Sprintf("ory_hydra_session_dev=.*; Path=%s; Expires=.*; Max-Age=0; HttpOnly; SameSite=Lax", cookiePath), setCookieHeader) }) t.Run("case=should pass and check if login context is set properly", func(t *testing.T) { // This should pass because login was remembered and session id should be set and session context should also work subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"fooz": "barz"}, }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.Equal(t, map[string]interface{}{"fooz": "barz"}, res.Context) assert.Equal(t, subject, *res.Subject) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}}) }) t.Run("case=perform flows with a public client", func(t *testing.T) { // This test covers old cases: // - This should fail because prompt=none, client is public, and redirection scheme is not HTTPS but a custom scheme and a custom domain // - This should fail because prompt=none, client is public, and redirection scheme is not HTTPS but a custom scheme // - This should pass because prompt=none, client is public, redirection scheme is HTTP and host is localhost c := &client.Client{LegacyClientID: uuidx.NewV4().String(), TokenEndpointAuthMethod: "none", RedirectURIs: []string{ testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler), "custom://redirection-scheme/path", "custom://localhost/path", }} require.NoError(t, reg.ClientManager().CreateClient(context.Background(), c)) subject := "aeneas-rekkas" testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true), RememberFor: pointerx.Int64(0)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true), RememberFor: pointerx.Int64(0)})) hc := testhelpers.NewEmptyJarClient(t) // set up initial session makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}}) // By not waiting here we ensure that there are no race conditions when it comes to authenticated_at and // requested_at time comparisons: // // time.Sleep(time.Second) t.Run("followup=should pass when prompt=none, redirection scheme is HTTP and host is localhost", func(t *testing.T) { makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}, "prompt": {"none"}}) }) t.Run("followup=should pass when prompt=none, redirection scheme is HTTP and host is a custom scheme", func(t *testing.T) { for _, redir := range c.RedirectURIs[1:] { t.Run("redir=should pass because prompt=none, client is public, and redirection is "+redir, func(t *testing.T) { _, err := hc.Get(urlx.CopyWithQuery(reg.Config().OAuth2AuthURL(ctx), url.Values{ "response_type": {"code"}, "state": {uuid.New()}, "redirect_uri": {redir}, "client_id": {c.GetID()}, "prompt": {"none"}, }).String()) require.Error(t, err) assert.Contains(t, err.Error(), redir) // https://tools.ietf.org/html/rfc6749 // // As stated in Section 10.2 of OAuth 2.0 [RFC6749], the authorization // server SHOULD NOT process authorization requests automatically // without user consent or interaction, except when the identity of the // client can be assured. This includes the case where the user has // previously approved an authorization request for a given client id -- // unless the identity of the client can be proven, the request SHOULD // be processed as if no previous request had been approved. // // Measures such as claimed "https" scheme redirects MAY be accepted by // authorization servers as identity proof. Some operating systems may // offer alternative platform-specific identity features that MAY be assert.Contains(t, err.Error(), "error=consent_required") }) } }) }) t.Run("case=should fail at login screen because subject in login challenge does not match subject from previous session", func(t *testing.T) { // Previously: This should fail at login screen because subject from accept does not match subject from session c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, nil)) // Init session hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) testhelpers.NewLoginConsentUI(t, reg.Config(), func(w http.ResponseWriter, r *http.Request) { _, res, err := adminClient.OAuth2Api.AcceptOAuth2LoginRequest(context.Background()). LoginChallenge(r.URL.Query().Get("login_challenge")). AcceptOAuth2LoginRequest(hydra.AcceptOAuth2LoginRequest{ Subject: "not-aeneas-rekkas", }).Execute() require.Error(t, err) assert.Contains(t, string(ioutilx.MustReadAll(res.Body)), "Field 'subject' does not match subject from previous authentication") w.WriteHeader(http.StatusBadRequest) }, testhelpers.HTTPServerNoExpectedCallHandler(t)) _, res := makeOAuth2Request(t, reg, hc, c, url.Values{}) assert.EqualValues(t, http.StatusBadRequest, res.StatusCode) assert.Empty(t, res.Request.URL.Query().Get("code")) }) t.Run("case=should require re-authentication when parameters mandate it", func(t *testing.T) { // Covers: // - should pass and require re-authentication although session is set (because prompt=login) // - should pass and require re-authentication although session is set (because max_age=1) subject := "aeneas-rekkas" c := createDefaultClient(t) resetUI := func(t *testing.T) { testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) assert.False(t, res.Skip) // Skip should always be false here return hydra.AcceptOAuth2LoginRequest{ Remember: pointerx.Bool(true), } }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), })) } resetUI(t) // Init session hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) for k, values := range []url.Values{ {"prompt": {"login"}}, {"max_age": {"1"}}, {"max_age": {"0"}}, } { t.Run("values="+values.Encode(), func(t *testing.T) { if k == 1 { // If this is the max_age case we need to wait for max age to pass. time.Sleep(time.Second) } resetUI(t) makeRequestAndExpectCode(t, hc, c, values) }) } }) t.Run("case=should fail because max_age=1 but prompt=none", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) time.Sleep(time.Second) makeRequestAndExpectError(t, hc, c, url.Values{"max_age": {"1"}, "prompt": {"none"}}, "prompt is set to 'none' and authentication time reached 'max_age'") }) t.Run("case=should fail because prompt is none but no auth session exists", func(t *testing.T) { c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) makeRequestAndExpectError(t, nil, c, url.Values{"prompt": {"none"}}, "Prompt 'none' was requested, but no existing login session was found") }) t.Run("case=should fail because prompt is none and consent is missing a permission which requires re-authorization of the app", func(t *testing.T) { c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, "aeneas-rekkas", &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) // Init cookie hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) // Make request with additional scope and prompt none, which fails makeRequestAndExpectError(t, hc, c, url.Values{"prompt": {"none"}, "scope": {"openid"}}, "Prompt 'none' was requested, but no previous consent was found") }) t.Run("case=pass and properly require authentication as well as authorization because prompt is set to login and consent although previous session exists", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { require.NoError(t, err) assert.False(t, res.Skip) // Skip should always be false here because prompt has login return hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)} }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.False(t, *res.Skip) // Skip should always be false here because prompt has consent return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), } })) // Init cookie hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) // Rerun with login and consent set makeRequestAndExpectCode(t, hc, c, url.Values{"prompt": {"login consent"}}) }) t.Run("case=should fail because id_token_hint does not match value from accepted login request", func(t *testing.T) { // Covers former tests: // - This should pass and require authentication because id_token_hint does not match subject from session // - This should fail because id_token_hint does not match authentication session and prompt is none // - This should fail because the user from the ID token does not match the user from the accept login request subject := "aeneas-rekkas" notSubject := "not-aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) // Init cookie hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) for _, values := range []url.Values{ {"prompt": {"none"}, "id_token_hint": {testhelpers.NewIDToken(t, reg, notSubject)}}, {"id_token_hint": {testhelpers.NewIDToken(t, reg, notSubject)}}, } { t.Run(fmt.Sprintf("values=%v", values), func(t *testing.T) { testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndAcceptLoginHandler(t, adminClient, subject, func(t *testing.T, res *hydra.OAuth2LoginRequest, err error) hydra.AcceptOAuth2LoginRequest { var b bytes.Buffer require.NoError(t, json.NewEncoder(&b).Encode(res)) assert.EqualValues(t, notSubject, gjson.GetBytes(b.Bytes(), "oidc_context.id_token_hint_claims.sub"), b.String()) return hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)} }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) makeRequestAndExpectError(t, hc, c, values, "Request failed because subject claim from id_token_hint does not match subject from authentication session") }) } }) t.Run("case=should pass and require authentication because id_token_hint does match subject from session", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) makeRequestAndExpectCode(t, nil, c, url.Values{"id_token_hint": {testhelpers.NewIDToken(t, reg, subject)}}) t.Run("case=should pass even though id_token_hint is expired", func(t *testing.T) { // Formerly: should pass as regularly even though id_token_hint is expired makeRequestAndExpectCode(t, nil, c, url.Values{ "id_token_hint": {testhelpers.NewIDTokenWithExpiry(t, reg, subject, -time.Hour)}}) }) }) t.Run("suite=pairwise auth", func(t *testing.T) { // Covers former tests: // - This should pass as regularly and create a new session with pairwise subject set by hydra // - This should pass as regularly and create a new session with pairwise subject and also with the ID token set c := createClient(t, reg, &client.Client{ SubjectType: "pairwise", SectorIdentifierURI: "foo", RedirectURIs: []string{testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)}, }) subject := "auth-user" hash := fmt.Sprintf("%x", sha256.Sum256([]byte(c.SectorIdentifierURI+subject+reg.Config().SubjectIdentifierAlgorithmSalt(ctx)))) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true), GrantScope: []string{"openid"}})) for _, tc := range []struct { d string values url.Values }{ { d: "check all the sub claims", values: url.Values{"scope": {"openid"}}, }, { d: "works with id_token_hint", values: url.Values{"scope": {"openid"}, "id_token_hint": {testhelpers.NewIDToken(t, reg, hash)}}, }, } { t.Run("case="+tc.d, func(t *testing.T) { code := makeRequestAndExpectCode(t, nil, c, tc.values) conf := oauth2Config(t, c) token, err := conf.Exchange(context.Background(), code) require.NoError(t, err) // OpenID data must be obfuscated idClaims := testhelpers.DecodeIDToken(t, token) assert.EqualValues(t, hash, idClaims.Get("sub").String()) uiClaims := testhelpers.Userinfo(t, token, publicTS) assert.EqualValues(t, hash, uiClaims.Get("sub").String()) // Access token data must not be obfuscated atClaims := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS) assert.EqualValues(t, subject, atClaims.Get("sub").String()) }) } }) t.Run("suite=pairwise auth with forced identifier", func(t *testing.T) { // Covers: // - This should pass as regularly and create a new session with pairwise subject set login request // - This should pass as regularly and create a new session with pairwise subject set on login request and also with the ID token set c := createClient(t, reg, &client.Client{ SubjectType: "pairwise", SectorIdentifierURI: "foo", RedirectURIs: []string{testhelpers.NewCallbackURL(t, "callback", testhelpers.HTTPServerNotImplementedHandler)}, }) subject := "aeneas-rekkas" obfuscated := "obfuscated-friedrich-kaiser" testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ ForceSubjectIdentifier: &obfuscated, }), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{GrantScope: []string{"openid"}})) code := makeRequestAndExpectCode(t, nil, c, url.Values{}) conf := oauth2Config(t, c) token, err := conf.Exchange(context.Background(), code) require.NoError(t, err) // OpenID data must be obfuscated idClaims := testhelpers.DecodeIDToken(t, token) assert.EqualValues(t, obfuscated, idClaims.Get("sub").String()) uiClaims := testhelpers.Userinfo(t, token, publicTS) assert.EqualValues(t, obfuscated, uiClaims.Get("sub").String()) // Access token data must not be obfuscated atClaims := testhelpers.IntrospectToken(t, conf, token.AccessToken, adminTS) assert.EqualValues(t, subject, atClaims.Get("sub").String()) }) t.Run("suite=properly clean up session cookies", func(t *testing.T) { t.Skip("This test is skipped because we forcibly set remember to true always when skip is also true for a better user experience.") subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(true)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(true)})) // Initialize flow // Formerly: This should pass as regularly and create a new session and forward data hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{}) // Re-run flow but do not remember login // Formerly: This should pass and also revoke the session cookie testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{Remember: pointerx.Bool(false)}), acceptConsentHandler(t, &hydra.AcceptOAuth2ConsentRequest{Remember: pointerx.Bool(false)})) makeRequestAndExpectCode(t, hc, c, url.Values{}) // Formerly: This should require re-authentication because the session was revoked in the previous test makeRequestAndExpectError(t, hc, c, url.Values{"prompt": {"none"}}, "...") }) t.Run("case=should require re-authentication because the session does not exist in the store", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, nil), acceptConsentHandler(t, nil)) hc := &http.Client{Jar: newAuthCookieJar(t, reg, publicTS.URL, "i-do-not-exist")} makeRequestAndExpectError(t, hc, c, url.Values{"prompt": {"none"}}, "The Authorization Server requires End-User authentication.") }) t.Run("case=should be able to retry accept consent request", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), acceptLoginHandler(t, subject, &hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"fooz": "barz"}, }), checkAndDuplicateAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.Equal(t, map[string]interface{}{"fooz": "barz"}, res.Context) assert.Equal(t, subject, *res.Subject) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}}) }) t.Run("case=should be able to retry accept login request", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndDuplicateAcceptLoginHandler(t, adminClient, subject, func(*testing.T, *hydra.OAuth2LoginRequest, error) hydra.AcceptOAuth2LoginRequest { return hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"fooz": "barz"}, } }), checkAndAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.Equal(t, map[string]interface{}{"fooz": "barz"}, res.Context) assert.Equal(t, subject, *res.Subject) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}}) }) t.Run("case=should be able to retry both accept login and consent requests", func(t *testing.T) { subject := "aeneas-rekkas" c := createDefaultClient(t) testhelpers.NewLoginConsentUI(t, reg.Config(), checkAndDuplicateAcceptLoginHandler(t, adminClient, subject, func(*testing.T, *hydra.OAuth2LoginRequest, error) hydra.AcceptOAuth2LoginRequest { return hydra.AcceptOAuth2LoginRequest{ Subject: subject, Context: map[string]interface{}{"fooz": "barz"}, } }), checkAndDuplicateAcceptConsentHandler(t, adminClient, func(t *testing.T, res *hydra.OAuth2ConsentRequest, err error) hydra.AcceptOAuth2ConsentRequest { require.NoError(t, err) assert.Equal(t, map[string]interface{}{"fooz": "barz"}, res.Context) assert.Equal(t, subject, *res.Subject) return hydra.AcceptOAuth2ConsentRequest{ Remember: pointerx.Bool(true), GrantScope: []string{"openid"}, Session: &hydra.AcceptOAuth2ConsentRequestSession{ AccessToken: map[string]interface{}{"foo": "bar"}, IdToken: map[string]interface{}{"bar": "baz"}, }, } })) hc := testhelpers.NewEmptyJarClient(t) makeRequestAndExpectCode(t, hc, c, url.Values{"redirect_uri": {c.RedirectURIs[0]}}) }) } func DropCookieJar(drop *regexp.Regexp) http.CookieJar { jar, _ := cookiejar.New(nil) return &dropCSRFCookieJar{ jar: jar, drop: drop, } } type dropCSRFCookieJar struct { jar *cookiejar.Jar drop *regexp.Regexp } var _ http.CookieJar = (*dropCSRFCookieJar)(nil) func (d *dropCSRFCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) { for _, c := range cookies { if d.drop.MatchString(c.Name) { continue } d.jar.SetCookies(u, []*http.Cookie{c}) } } func (d *dropCSRFCookieJar) Cookies(u *url.URL) []*http.Cookie { return d.jar.Cookies(u) } func newHTTPClientWithFlowCookie(t *testing.T, ctx context.Context, reg interface { ConsentManager() consent.Manager Config() *config.DefaultProvider FlowCipher() *aead.XChaCha20Poly1305 }, c *client.Client) *http.Client { f, err := reg.ConsentManager().CreateLoginRequest(ctx, &flow.LoginRequest{Client: c}) require.NoError(t, err) hc := testhelpers.NewEmptyJarClient(t) hc.Jar.SetCookies(reg.Config().OAuth2AuthURL(ctx), []*http.Cookie{ {Name: flowctx.FlowCookie(c), Value: x.Must(flowctx.Encode(ctx, reg.FlowCipher(), f))}, }) return hc }
Go
hydra/consent/subject_identifier_algorithm.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import "github.com/ory/hydra/v2/client" type SubjectIdentifierAlgorithm interface { // Obfuscate derives a pairwise subject identifier from the given string. Obfuscate(subject string, client *client.Client) (string, error) }
Go
hydra/consent/subject_identifier_algorithm_pairwise.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import ( "crypto/sha256" "fmt" "net/url" "github.com/ory/x/errorsx" "github.com/ory/fosite" "github.com/ory/hydra/v2/client" ) type SubjectIdentifierAlgorithmPairwise struct { Salt []byte } func NewSubjectIdentifierAlgorithmPairwise(salt []byte) *SubjectIdentifierAlgorithmPairwise { return &SubjectIdentifierAlgorithmPairwise{Salt: salt} } func (g *SubjectIdentifierAlgorithmPairwise) Obfuscate(subject string, client *client.Client) (string, error) { // sub = SHA-256 ( sector_identifier || local_account_id || salt ). var id string if len(client.SectorIdentifierURI) == 0 && len(client.RedirectURIs) > 1 { return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("OAuth 2.0 Client %s has multiple redirect_uris but no sector_identifier_uri was set which is not allowed when performing using subject type pairwise. Please reconfigure the OAuth 2.0 client properly.", client.GetID())) } else if len(client.SectorIdentifierURI) == 0 && len(client.RedirectURIs) == 0 { return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("OAuth 2.0 Client %s neither specifies a sector_identifier_uri nor a redirect_uri which is not allowed when performing using subject type pairwise. Please reconfigure the OAuth 2.0 client properly.", client.GetID())) } else if len(client.SectorIdentifierURI) > 0 { id = client.SectorIdentifierURI } else { redirectURL, err := url.Parse(client.RedirectURIs[0]) if err != nil { return "", errorsx.WithStack(err) } id = redirectURL.Host } return fmt.Sprintf("%x", sha256.Sum256(append(append([]byte{}, []byte(id+subject)...), g.Salt...))), nil }
Go
hydra/consent/subject_identifier_algorithm_public.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package consent import "github.com/ory/hydra/v2/client" type SubjectIdentifierAlgorithmPublic struct{} func NewSubjectIdentifierAlgorithmPublic() *SubjectIdentifierAlgorithmPublic { return &SubjectIdentifierAlgorithmPublic{} } func (g *SubjectIdentifierAlgorithmPublic) Obfuscate(subject string, client *client.Client) (string, error) { return subject, nil }
YAML
hydra/contrib/quickstart/quickstart-gitlab.yml
version: "3" services: gitlab: image: gitlab/gitlab-ce:13.3.2-ce.0 restart: always hostname: gitlab.example.com environment: GITLAB_OMNIBUS_CONFIG: | external_url 'http://gitlab.example.com:8000/' ports: - "443:443" # https - "8000:8000" # http - "2222:22" # ssh volumes: - "./contrib/quickstart/gitlab/config:/etc/gitlab" - "./contrib/quickstart/gitlab/logs:/var/log/gitlab" - "./contrib/quickstart/gitlab/data:/var/opt/gitlab"
YAML
hydra/contrib/quickstart/5-min/hydra.yml
serve: cookies: same_site_mode: Lax urls: self: issuer: http://127.0.0.1:4444 consent: http://127.0.0.1:3000/consent login: http://127.0.0.1:3000/login logout: http://127.0.0.1:3000/logout secrets: system: - youReallyNeedToChangeThis oidc: subject_identifiers: supported_types: - pairwise - public pairwise: salt: youReallyNeedToChangeThis
Ruby
hydra/contrib/quickstart/gitlab/config/gitlab.rb
# Copyright © 2022 Ory Corp # SPDX-License-Identifier: Apache-2.0 ## GitLab configuration settings ##! This file is generated during initial installation and **is not** modified ##! during upgrades. ##! Check out the latest version of this file to know about the different ##! settings that can be configured by this file, which may be found at: ##! https://gitlab.com/gitlab-org/omnibus-gitlab/raw/master/files/gitlab-config-template/gitlab.rb.template ##! You can run `gitlab-ctl diff-config` to compare the contents of the current gitlab.rb with ##! the gitlab.rb.template from the currently running version. ##! You can run `gitlab-ctl show-config` to display the configuration that will be generated by ##! running `gitlab-ctl reconfigure` ##! In general, the values specified here should reflect what the default value of the attribute will be. ##! There are instances where this behavior is not possible or desired. For example, when providing passwords, ##! or connecting to third party services. ##! In those instances, we endeavour to provide an example configuration. ## GitLab URL ##! URL on which GitLab will be reachable. ##! For more details on configuring external_url see: ##! https://docs.gitlab.com/omnibus/settings/configuration.html#configuring-the-external-url-for-gitlab ##! ##! Note: During installation/upgrades, the value of the environment variable ##! EXTERNAL_URL will be used to populate/replace this value. ##! On AWS EC2 instances, we also attempt to fetch the public hostname/IP ##! address from AWS. For more details, see: ##! https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html # external_url 'GENERATED_EXTERNAL_URL' ## Roles for multi-instance GitLab ##! The default is to have no roles enabled, which results in GitLab running as an all-in-one instance. ##! Options: ##! redis_sentinel_role redis_master_role redis_replica_role geo_primary_role geo_secondary_role ##! postgres_role consul_role application_role monitoring_role ##! For more details on each role, see: ##! https://docs.gitlab.com/omnibus/roles/README.html#roles ##! # roles ['redis_sentinel_role', 'redis_master_role'] ## Legend ##! The following notations at the beginning of each line may be used to ##! differentiate between components of this file and to easily select them using ##! a regex. ##! ## Titles, subtitles etc ##! ##! More information - Description, Docs, Links, Issues etc. ##! Configuration settings have a single # followed by a single space at the ##! beginning; Remove them to enable the setting. ##! **Configuration settings below are optional.** ################################################################################ ################################################################################ ## Configuration Settings for GitLab CE and EE ## ################################################################################ ################################################################################ ################################################################################ ## gitlab.yml configuration ##! Docs: https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/doc/settings/gitlab.yml.md ################################################################################ # gitlab_rails['gitlab_ssh_host'] = 'ssh.host_example.com' # gitlab_rails['gitlab_ssh_user'] = '' # gitlab_rails['time_zone'] = 'UTC' ### Request duration ###! Tells the rails application how long it has to complete a request ###! This value needs to be lower than the worker timeout set in unicorn/puma. ###! By default, we'll allow 95% of the the worker timeout # gitlab_rails['max_request_duration_seconds'] = 57 ### Email Settings # gitlab_rails['gitlab_email_enabled'] = true # gitlab_rails['gitlab_email_from'] = '[email protected]' # gitlab_rails['gitlab_email_display_name'] = 'Example' # gitlab_rails['gitlab_email_reply_to'] = '[email protected]' # gitlab_rails['gitlab_email_subject_suffix'] = '' # gitlab_rails['gitlab_email_smime_enabled'] = false # gitlab_rails['gitlab_email_smime_key_file'] = '/etc/gitlab/ssl/gitlab_smime.key' # gitlab_rails['gitlab_email_smime_cert_file'] = '/etc/gitlab/ssl/gitlab_smime.crt' # gitlab_rails['gitlab_email_smime_ca_certs_file'] = '/etc/gitlab/ssl/gitlab_smime_cas.crt' ### GitLab user privileges # gitlab_rails['gitlab_default_can_create_group'] = true # gitlab_rails['gitlab_username_changing_enabled'] = true ### Default Theme # gitlab_rails['gitlab_default_theme'] = 2 ### Default project feature settings # gitlab_rails['gitlab_default_projects_features_issues'] = true # gitlab_rails['gitlab_default_projects_features_merge_requests'] = true # gitlab_rails['gitlab_default_projects_features_wiki'] = true # gitlab_rails['gitlab_default_projects_features_snippets'] = true # gitlab_rails['gitlab_default_projects_features_builds'] = true # gitlab_rails['gitlab_default_projects_features_container_registry'] = true ### Automatic issue closing ###! See https://docs.gitlab.com/ee/customization/issue_closing.html for more ###! information about this pattern. # gitlab_rails['gitlab_issue_closing_pattern'] = "\b((?:[Cc]los(?:e[sd]?|ing)|\b[Ff]ix(?:e[sd]|ing)?|\b[Rr]esolv(?:e[sd]?|ing)|\b[Ii]mplement(?:s|ed|ing)?)(:?) +(?:(?:issues? +)?%{issue_ref}(?:(?:, *| +and +)?)|([A-Z][A-Z0-9_]+-\d+))+)" ### Download location ###! When a user clicks e.g. 'Download zip' on a project, a temporary zip file ###! is created in the following directory. ###! Should not be the same path, or a sub directory of any of the `git_data_dirs` # gitlab_rails['gitlab_repository_downloads_path'] = 'tmp/repositories' ### Gravatar Settings # gitlab_rails['gravatar_plain_url'] = 'http://www.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon' # gitlab_rails['gravatar_ssl_url'] = 'https://secure.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon' ### Auxiliary jobs ###! Periodically executed jobs, to self-heal Gitlab, do external ###! synchronizations, etc. ###! Docs: https://github.com/ondrejbartas/sidekiq-cron#adding-cron-job ###! https://docs.gitlab.com/ee/ci/yaml/README.html#artifactsexpire_in # gitlab_rails['stuck_ci_jobs_worker_cron'] = "0 0 * * *" # gitlab_rails['expire_build_artifacts_worker_cron'] = "50 * * * *" # gitlab_rails['environments_auto_stop_cron_worker_cron'] = "24 * * * *" # gitlab_rails['pipeline_schedule_worker_cron'] = "19 * * * *" # gitlab_rails['ci_archive_traces_cron_worker_cron'] = "17 * * * *" # gitlab_rails['repository_check_worker_cron'] = "20 * * * *" # gitlab_rails['admin_email_worker_cron'] = "0 0 * * 0" # gitlab_rails['personal_access_tokens_expiring_worker_cron'] = "0 1 * * *" # gitlab_rails['repository_archive_cache_worker_cron'] = "0 * * * *" # gitlab_rails['pages_domain_verification_cron_worker'] = "*/15 * * * *" # gitlab_rails['pages_domain_ssl_renewal_cron_worker'] = "*/10 * * * *" # gitlab_rails['pages_domain_removal_cron_worker'] = "47 0 * * *" # gitlab_rails['schedule_migrate_external_diffs_worker_cron'] = "15 * * * *" ### Webhook Settings ###! Number of seconds to wait for HTTP response after sending webhook HTTP POST ###! request (default: 10) # gitlab_rails['webhook_timeout'] = 10 ### GraphQL Settings ###! Tells the rails application how long it has to complete a GraphQL request. ###! We suggest this value to be higher than the database timeout value ###! and lower than the worker timeout set in unicorn/puma. (default: 30) # gitlab_rails['graphql_timeout'] = 30 ### Trusted proxies ###! Customize if you have GitLab behind a reverse proxy which is running on a ###! different machine. ###! **Add the IP address for your reverse proxy to the list, otherwise users ###! will appear signed in from that address.** # gitlab_rails['trusted_proxies'] = [] ### Content Security Policy ####! Customize if you want to enable the Content-Security-Policy header, which ####! can help thwart JavaScript cross-site scripting (XSS) attacks. ####! See: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP # gitlab_rails['content_security_policy'] = { # 'enabled' => false, # 'report_only' => false, # # Each directive is a String (e.g. "'self'"). # 'directives' => { # 'base_uri' => nil, # 'child_src' => nil, # 'connect_src' => nil, # 'default_src' => nil, # 'font_src' => nil, # 'form_action' => nil, # 'frame_ancestors' => nil, # 'frame_src' => nil, # 'img_src' => nil, # 'manifest_src' => nil, # 'media_src' => nil, # 'object_src' => nil, # 'script_src' => nil, # 'style_src' => nil, # 'worker_src' => nil, # 'report_uri' => nil, # } # } ### Monitoring settings ###! IP whitelist controlling access to monitoring endpoints # gitlab_rails['monitoring_whitelist'] = ['127.0.0.0/8', '::1/128'] ###! Time between sampling of unicorn socket metrics, in seconds # gitlab_rails['monitoring_unicorn_sampler_interval'] = 10 ### Shutdown settings ###! Defines an interval to block healthcheck, ###! but continue accepting application requests. # gitlab_rails['shutdown_blackout_seconds'] = 10 ### Reply by email ###! Allow users to comment on issues and merge requests by replying to ###! notification emails. ###! Docs: https://docs.gitlab.com/ee/administration/reply_by_email.html # gitlab_rails['incoming_email_enabled'] = true #### Incoming Email Address ####! The email address including the `%{key}` placeholder that will be replaced ####! to reference the item being replied to. ####! **The placeholder can be omitted but if present, it must appear in the ####! "user" part of the address (before the `@`).** # gitlab_rails['incoming_email_address'] = "gitlab-incoming+%{key}@gmail.com" #### Email account username ####! **With third party providers, this is usually the full email address.** ####! **With self-hosted email servers, this is usually the user part of the ####! email address.** # gitlab_rails['incoming_email_email'] = "[email protected]" #### Email account password # gitlab_rails['incoming_email_password'] = "[REDACTED]" #### IMAP Settings # gitlab_rails['incoming_email_host'] = "imap.gmail.com" # gitlab_rails['incoming_email_port'] = 993 # gitlab_rails['incoming_email_ssl'] = true # gitlab_rails['incoming_email_start_tls'] = false #### Incoming Mailbox Settings (via `mail_room`) ####! The mailbox where incoming mail will end up. Usually "inbox". # gitlab_rails['incoming_email_mailbox_name'] = "inbox" ####! The IDLE command timeout. # gitlab_rails['incoming_email_idle_timeout'] = 60 ####! The file name for internal `mail_room` JSON logfile # gitlab_rails['incoming_email_log_file'] = "/var/log/gitlab/mailroom/mail_room_json.log" ####! Permanently remove messages from the mailbox when they are deleted after delivery # gitlab_rails['incoming_email_expunge_deleted'] = false ####! The format of mail_room crash logs # mailroom['exit_log_format'] = "plain" ### Job Artifacts # gitlab_rails['artifacts_enabled'] = true # gitlab_rails['artifacts_path'] = "/var/opt/gitlab/gitlab-rails/shared/artifacts" ####! Job artifacts Object Store ####! Docs: https://docs.gitlab.com/ee/administration/job_artifacts.html#using-object-storage # gitlab_rails['artifacts_object_store_enabled'] = false # gitlab_rails['artifacts_object_store_direct_upload'] = false # gitlab_rails['artifacts_object_store_background_upload'] = true # gitlab_rails['artifacts_object_store_proxy_download'] = false # gitlab_rails['artifacts_object_store_remote_directory'] = "artifacts" # gitlab_rails['artifacts_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'host' => 's3.amazonaws.com', # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ### External merge request diffs # gitlab_rails['external_diffs_enabled'] = false # gitlab_rails['external_diffs_when'] = nil # gitlab_rails['external_diffs_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/external-diffs" # gitlab_rails['external_diffs_object_store_enabled'] = false # gitlab_rails['external_diffs_object_store_direct_upload'] = false # gitlab_rails['external_diffs_object_store_background_upload'] = false # gitlab_rails['external_diffs_object_store_proxy_download'] = false # gitlab_rails['external_diffs_object_store_remote_directory'] = "external-diffs" # gitlab_rails['external_diffs_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'host' => 's3.amazonaws.com', # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ### Git LFS # gitlab_rails['lfs_enabled'] = true # gitlab_rails['lfs_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/lfs-objects" # gitlab_rails['lfs_object_store_enabled'] = false # gitlab_rails['lfs_object_store_direct_upload'] = false # gitlab_rails['lfs_object_store_background_upload'] = true # gitlab_rails['lfs_object_store_proxy_download'] = false # gitlab_rails['lfs_object_store_remote_directory'] = "lfs-objects" # gitlab_rails['lfs_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'host' => 's3.amazonaws.com', # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ### GitLab uploads ###! Docs: https://docs.gitlab.com/ee/administration/uploads.html # gitlab_rails['uploads_storage_path'] = "/opt/gitlab/embedded/service/gitlab-rails/public" # gitlab_rails['uploads_base_dir'] = "uploads/-/system" # gitlab_rails['uploads_object_store_enabled'] = false # gitlab_rails['uploads_object_store_direct_upload'] = false # gitlab_rails['uploads_object_store_background_upload'] = true # gitlab_rails['uploads_object_store_proxy_download'] = false # gitlab_rails['uploads_object_store_remote_directory'] = "uploads" # gitlab_rails['uploads_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'host' => 's3.amazonaws.com', # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ### Terraform state ###! Docs: https://docs.gitlab.com/ee/administration/terraform_state # gitlab_rails['terraform_state_enabled'] = true # gitlab_rails['terraform_state_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/terraform_state" # gitlab_rails['terraform_state_object_store_enabled'] = false # gitlab_rails['terraform_state_object_store_remote_directory'] = "terraform_state" # gitlab_rails['terraform_state_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'host' => 's3.amazonaws.com', # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ### Impersonation settings # gitlab_rails['impersonation_enabled'] = true ### Usage Statistics # gitlab_rails['usage_ping_enabled'] = true ### Seat Link setting ###! Docs: https://docs.gitlab.com/ee/subscriptions/index.html#seat-link # gitlab_rails['seat_link_enabled'] = true ### GitLab Mattermost ###! These settings are void if Mattermost is installed on the same omnibus ###! install # gitlab_rails['mattermost_host'] = "https://mattermost.example.com" ### LDAP Settings ###! Docs: https://docs.gitlab.com/omnibus/settings/ldap.html ###! **Be careful not to break the indentation in the ldap_servers block. It is ###! in yaml format and the spaces must be retained. Using tabs will not work.** # gitlab_rails['ldap_enabled'] = false # gitlab_rails['prevent_ldap_sign_in'] = false ###! **remember to close this block with 'EOS' below** # gitlab_rails['ldap_servers'] = YAML.load <<-'EOS' # main: # 'main' is the GitLab 'provider ID' of this LDAP server # label: 'LDAP' # host: '_your_ldap_server' # port: 389 # uid: 'sAMAccountName' # bind_dn: '_the_full_dn_of_the_user_you_will_bind_with' # password: '_the_password_of_the_bind_user' # encryption: 'plain' # "start_tls" or "simple_tls" or "plain" # verify_certificates: true # smartcard_auth: false # active_directory: true # allow_username_or_email_login: false # lowercase_usernames: false # block_auto_created_users: false # base: '' # user_filter: '' # ## EE only # group_base: '' # admin_group: '' # sync_ssh_keys: false # # secondary: # 'secondary' is the GitLab 'provider ID' of second LDAP server # label: 'LDAP' # host: '_your_ldap_server' # port: 389 # uid: 'sAMAccountName' # bind_dn: '_the_full_dn_of_the_user_you_will_bind_with' # password: '_the_password_of_the_bind_user' # encryption: 'plain' # "start_tls" or "simple_tls" or "plain" # verify_certificates: true # smartcard_auth: false # active_directory: true # allow_username_or_email_login: false # lowercase_usernames: false # block_auto_created_users: false # base: '' # user_filter: '' # ## EE only # group_base: '' # admin_group: '' # sync_ssh_keys: false # EOS ### Smartcard authentication settings ###! Docs: https://docs.gitlab.com/ee/administration/auth/smartcard.html # gitlab_rails['smartcard_enabled'] = false # gitlab_rails['smartcard_ca_file'] = "/etc/gitlab/ssl/CA.pem" # gitlab_rails['smartcard_client_certificate_required_host'] = 'smartcard.gitlab.example.com' # gitlab_rails['smartcard_client_certificate_required_port'] = 3444 # gitlab_rails['smartcard_required_for_git_access'] = false # gitlab_rails['smartcard_san_extensions'] = false ### OmniAuth Settings ###! Docs: https://docs.gitlab.com/ee/integration/omniauth.html # gitlab_rails['omniauth_enabled'] = nil # gitlab_rails['omniauth_allow_single_sign_on'] = ['saml'] # gitlab_rails['omniauth_sync_email_from_provider'] = 'saml' # gitlab_rails['omniauth_sync_profile_from_provider'] = ['saml'] # gitlab_rails['omniauth_sync_profile_attributes'] = ['email'] # gitlab_rails['omniauth_auto_sign_in_with_provider'] = 'saml' # gitlab_rails['omniauth_block_auto_created_users'] = true # gitlab_rails['omniauth_auto_link_ldap_user'] = false # gitlab_rails['omniauth_auto_link_saml_user'] = false # gitlab_rails['omniauth_external_providers'] = ['twitter', 'google_oauth2'] # gitlab_rails['omniauth_allow_bypass_two_factor'] = ['google_oauth2'] # gitlab_rails['omniauth_providers'] = [ # { # "name" => "google_oauth2", # "app_id" => "YOUR APP ID", # "app_secret" => "YOUR APP SECRET", # "args" => { "access_type" => "offline", "approval_prompt" => "" } # } # ] gitlab_rails['omniauth_enabled'] = true gitlab_rails['omniauth_block_auto_created_users'] = false gitlab_rails['omniauth_allow_single_sign_on'] = ['ORY_Hydra'] gitlab_rails['omniauth_providers'] = [ { 'name' => 'oauth2_generic', 'app_id' => 'gitlab', 'app_secret' => 'theSecret', 'args' => { client_options: { 'site' => 'http://127.0.0.1:4444', # including port if necessary 'user_info_url' => 'http://hydra:4444/userinfo', 'authorize_url' => 'http://127.0.0.1:4444/oauth2/auth', 'token_url' => 'http://hydra:4444/oauth2/token' }, user_response_structure: { root_path: [], id_path: 'sub', attributes: { email: 'sub' } }, authorize_params: { scope: 'email' }, # optionally, you can add the following two lines to "white label" the display name # of this strategy (appears in urls and Gitlab login buttons) # If you do this, you must also replace oauth2_generic, everywhere it appears above, with the new name. name: 'ORY_Hydra', # display name for this strategy #strategy_class: "OmniAuth::Strategies::OAuth2Generic" # Devise-specific config option Gitlab uses to find renamed strategy } } ] ### Backup Settings ###! Docs: https://docs.gitlab.com/omnibus/settings/backups.html # gitlab_rails['manage_backup_path'] = true # gitlab_rails['backup_path'] = "/var/opt/gitlab/backups" ###! Docs: https://docs.gitlab.com/ee/raketasks/backup_restore.html#backup-archive-permissions # gitlab_rails['backup_archive_permissions'] = 0644 # gitlab_rails['backup_pg_schema'] = 'public' ###! The duration in seconds to keep backups before they are allowed to be deleted # gitlab_rails['backup_keep_time'] = 604800 # gitlab_rails['backup_upload_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AKIAKIAKI', # 'aws_secret_access_key' => 'secret123', # # # If IAM profile use is enabled, remove aws_access_key_id and aws_secret_access_key # 'use_iam_profile' => false # } # gitlab_rails['backup_upload_remote_directory'] = 'my.s3.bucket' # gitlab_rails['backup_multipart_chunk_size'] = 104857600 ###! **Turns on AWS Server-Side Encryption with Amazon S3-Managed Keys for ###! backups** # gitlab_rails['backup_encryption'] = 'AES256' ###! The encryption key to use with AWS Server-Side Encryption. ###! Setting this value will enable Server-Side Encryption with customer provided keys; ###! otherwise S3-managed keys are used. # gitlab_rails['backup_encryption_key'] = '<base64-encoded encryption key>' ###! **Specifies Amazon S3 storage class to use for backups. Valid values ###! include 'STANDARD', 'STANDARD_IA', and 'REDUCED_REDUNDANCY'** # gitlab_rails['backup_storage_class'] = 'STANDARD' ###! Skip parts of the backup. Comma separated. ###! Docs: https://docs.gitlab.com/ee/raketasks/backup_restore.html#excluding-specific-directories-from-the-backup #gitlab_rails['env'] = { # "SKIP" => "db,uploads,repositories,builds,artifacts,lfs,registry,pages" #} ### Pseudonymizer Settings # gitlab_rails['pseudonymizer_manifest'] = 'config/pseudonymizer.yml' # gitlab_rails['pseudonymizer_upload_remote_directory'] = 'gitlab-elt' # gitlab_rails['pseudonymizer_upload_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AKIAKIAKI', # 'aws_secret_access_key' => 'secret123' # } ### For setting up different data storing directory ###! Docs: https://docs.gitlab.com/omnibus/settings/configuration.html#storing-git-data-in-an-alternative-directory ###! **If you want to use a single non-default directory to store git data use a ###! path that doesn't contain symlinks.** # git_data_dirs({ # "default" => { # "path" => "/mnt/nfs-01/git-data" # } # }) ### Gitaly settings # gitlab_rails['gitaly_token'] = 'secret token' ### For storing GitLab application uploads, eg. LFS objects, build artifacts ###! Docs: https://docs.gitlab.com/ee/development/shared_files.html # gitlab_rails['shared_path'] = '/var/opt/gitlab/gitlab-rails/shared' ### Wait for file system to be mounted ###! Docs: https://docs.gitlab.com/omnibus/settings/configuration.html#only-start-omnibus-gitlab-services-after-a-given-filesystem-is-mounted # high_availability['mountpoint'] = ["/var/opt/gitlab/git-data", "/var/opt/gitlab/gitlab-rails/shared"] ### GitLab Shell settings for GitLab # gitlab_rails['gitlab_shell_ssh_port'] = 22 # gitlab_rails['gitlab_shell_git_timeout'] = 800 ### Extra customization # gitlab_rails['extra_google_analytics_id'] = '_your_tracking_id' # gitlab_rails['extra_piwik_url'] = '_your_piwik_url' # gitlab_rails['extra_piwik_site_id'] = '_your_piwik_site_id' ##! Docs: https://docs.gitlab.com/omnibus/settings/environment-variables.html # gitlab_rails['env'] = { # 'BUNDLE_GEMFILE' => "/opt/gitlab/embedded/service/gitlab-rails/Gemfile", # 'PATH' => "/opt/gitlab/bin:/opt/gitlab/embedded/bin:/bin:/usr/bin" # } # gitlab_rails['rack_attack_git_basic_auth'] = { # 'enabled' => false, # 'ip_whitelist' => ["127.0.0.1"], # 'maxretry' => 10, # 'findtime' => 60, # 'bantime' => 3600 # } ###! **We do not recommend changing these directories.** # gitlab_rails['dir'] = "/var/opt/gitlab/gitlab-rails" # gitlab_rails['log_directory'] = "/var/log/gitlab/gitlab-rails" ### GitLab application settings # gitlab_rails['uploads_directory'] = "/var/opt/gitlab/gitlab-rails/uploads" #### Change the initial default admin password and shared runner registration tokens. ####! **Only applicable on initial setup, changing these settings after database ####! is created and seeded won't yield any change.** # gitlab_rails['initial_root_password'] = "password" # gitlab_rails['initial_shared_runners_registration_token'] = "token" #### Set path to an initial license to be used while bootstrapping GitLab. ####! **Only applicable on initial setup, future license updations need to be done via UI. ####! Updating the file specified in this path won't yield any change after the first reconfigure run. # gitlab_rails['initial_license_file'] = '/etc/gitlab/company.gitlab-license' #### Enable or disable automatic database migrations # gitlab_rails['auto_migrate'] = true #### This is advanced feature used by large gitlab deployments where loading #### whole RAILS env takes a lot of time. # gitlab_rails['rake_cache_clear'] = true ### GitLab database settings ###! Docs: https://docs.gitlab.com/omnibus/settings/database.html ###! **Only needed if you use an external database.** # gitlab_rails['db_adapter'] = "postgresql" # gitlab_rails['db_encoding'] = "unicode" # gitlab_rails['db_collation'] = nil # gitlab_rails['db_database'] = "gitlabhq_production" # gitlab_rails['db_pool'] = 1 # gitlab_rails['db_username'] = "gitlab" # gitlab_rails['db_password'] = nil # gitlab_rails['db_host'] = nil # gitlab_rails['db_port'] = 5432 # gitlab_rails['db_socket'] = nil # gitlab_rails['db_sslmode'] = nil # gitlab_rails['db_sslcompression'] = 0 # gitlab_rails['db_sslrootcert'] = nil # gitlab_rails['db_sslcert'] = nil # gitlab_rails['db_sslkey'] = nil # gitlab_rails['db_prepared_statements'] = false # gitlab_rails['db_statements_limit'] = 1000 ### GitLab Redis settings ###! Connect to your own Redis instance ###! Docs: https://docs.gitlab.com/omnibus/settings/redis.html #### Redis TCP connection # gitlab_rails['redis_host'] = "127.0.0.1" # gitlab_rails['redis_port'] = 6379 # gitlab_rails['redis_ssl'] = false # gitlab_rails['redis_password'] = nil # gitlab_rails['redis_database'] = 0 # gitlab_rails['redis_enable_client'] = true #### Redis local UNIX socket (will be disabled if TCP method is used) # gitlab_rails['redis_socket'] = "/var/opt/gitlab/redis/redis.socket" #### Sentinel support ####! To have Sentinel working, you must enable Redis TCP connection support ####! above and define a few Sentinel hosts below (to get a reliable setup ####! at least 3 hosts). ####! **You don't need to list every sentinel host, but the ones not listed will ####! not be used in a fail-over situation to query for the new master.** # gitlab_rails['redis_sentinels'] = [ # {'host' => '127.0.0.1', 'port' => 26379}, # ] #### Separate instances support ###! Docs: https://docs.gitlab.com/omnibus/settings/redis.html#running-with-multiple-redis-instances # gitlab_rails['redis_cache_instance'] = nil # gitlab_rails['redis_cache_sentinels'] = nil # gitlab_rails['redis_queues_instance'] = nil # gitlab_rails['redis_queues_sentinels'] = nil # gitlab_rails['redis_shared_state_instance'] = nil # gitlab_rails['redis_shared_sentinels'] = nil # gitlab_rails['redis_actioncable_instance'] = nil # gitlab_rails['redis_actioncable_sentinels'] = nil ### GitLab email server settings ###! Docs: https://docs.gitlab.com/omnibus/settings/smtp.html ###! **Use smtp instead of sendmail/postfix.** # gitlab_rails['smtp_enable'] = true # gitlab_rails['smtp_address'] = "smtp.server" # gitlab_rails['smtp_port'] = 465 # gitlab_rails['smtp_user_name'] = "smtp user" # gitlab_rails['smtp_password'] = "smtp password" # gitlab_rails['smtp_domain'] = "example.com" # gitlab_rails['smtp_authentication'] = "login" # gitlab_rails['smtp_enable_starttls_auto'] = true # gitlab_rails['smtp_tls'] = false ###! **Can be: 'none', 'peer', 'client_once', 'fail_if_no_peer_cert'** ###! Docs: http://api.rubyonrails.org/classes/ActionMailer/Base.html # gitlab_rails['smtp_openssl_verify_mode'] = 'none' # gitlab_rails['smtp_ca_path'] = "/etc/ssl/certs" # gitlab_rails['smtp_ca_file'] = "/etc/ssl/certs/ca-certificates.crt" ################################################################################ ## Container Registry settings ##! Docs: https://docs.gitlab.com/ee/administration/container_registry.html ################################################################################ # registry_external_url 'https://registry.example.com' ### Settings used by GitLab application # gitlab_rails['registry_enabled'] = true # gitlab_rails['registry_host'] = "registry.gitlab.example.com" # gitlab_rails['registry_port'] = "5005" # gitlab_rails['registry_path'] = "/var/opt/gitlab/gitlab-rails/shared/registry" # Notification secret, it's used to authenticate notification requests to GitLab application # You only need to change this when you use external Registry service, otherwise # it will be taken directly from notification settings of your Registry # gitlab_rails['registry_notification_secret'] = nil ###! **Do not change the following 3 settings unless you know what you are ###! doing** # gitlab_rails['registry_api_url'] = "http://localhost:5000" # gitlab_rails['registry_key_path'] = "/var/opt/gitlab/gitlab-rails/certificate.key" # gitlab_rails['registry_issuer'] = "omnibus-gitlab-issuer" ### Settings used by Registry application # registry['enable'] = true # registry['username'] = "registry" # registry['group'] = "registry" # registry['uid'] = nil # registry['gid'] = nil # registry['dir'] = "/var/opt/gitlab/registry" # registry['registry_http_addr'] = "localhost:5000" # registry['debug_addr'] = "localhost:5001" # registry['log_directory'] = "/var/log/gitlab/registry" # registry['env_directory'] = "/opt/gitlab/etc/registry/env" # registry['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } # registry['log_level'] = "info" # registry['log_formatter'] = "text" # registry['rootcertbundle'] = "/var/opt/gitlab/registry/certificate.crt" # registry['health_storagedriver_enabled'] = true # registry['storage_delete_enabled'] = true # registry['validation_enabled'] = false # registry['autoredirect'] = false # registry['compatibility_schema1_enabled'] = false ### Registry backend storage ###! Docs: https://docs.gitlab.com/ee/administration/container_registry.html#container-registry-storage-driver # registry['storage'] = { # 's3' => { # 'accesskey' => 'AKIAKIAKI', # 'secretkey' => 'secret123', # 'region' => 'us-east-1', # 'bucket' => 'gitlab-registry-bucket-AKIAKIAKI' # } # } ### Registry notifications endpoints # registry['notifications'] = [ # { # 'name' => 'test_endpoint', # 'url' => 'https://gitlab.example.com/notify2', # 'timeout' => '500ms', # 'threshold' => 5, # 'backoff' => '1s', # 'headers' => { # "Authorization" => ["AUTHORIZATION_EXAMPLE_TOKEN"] # } # } # ] ### Default registry notifications # registry['default_notifications_timeout'] = "500ms" # registry['default_notifications_threshold'] = 5 # registry['default_notifications_backoff'] = "1s" # registry['default_notifications_headers'] = {} ################################################################################ ## Error Reporting and Logging with Sentry ################################################################################ # gitlab_rails['sentry_enabled'] = false # gitlab_rails['sentry_dsn'] = 'https://<key>@sentry.io/<project>' # gitlab_rails['sentry_clientside_dsn'] = 'https://<key>@sentry.io/<project>' # gitlab_rails['sentry_environment'] = 'production' ################################################################################ ## CI_JOB_JWT ################################################################################ ##! RSA private key used to sign CI_JOB_JWT # gitlab_rails['ci_jwt_signing_key'] = nil # Will be generated if not set. ################################################################################ ## GitLab Workhorse ##! Docs: https://gitlab.com/gitlab-org/gitlab-workhorse/blob/master/README.md ################################################################################ # gitlab_workhorse['enable'] = true # gitlab_workhorse['ha'] = false # gitlab_workhorse['listen_network'] = "unix" # gitlab_workhorse['listen_umask'] = 000 # gitlab_workhorse['listen_addr'] = "/var/opt/gitlab/gitlab-workhorse/socket" # gitlab_workhorse['auth_backend'] = "http://localhost:8080" ##! the empty string is the default in gitlab-workhorse option parser # gitlab_workhorse['auth_socket'] = "''" ##! put an empty string on the command line # gitlab_workhorse['pprof_listen_addr'] = "''" # gitlab_workhorse['prometheus_listen_addr'] = "localhost:9229" # gitlab_workhorse['dir'] = "/var/opt/gitlab/gitlab-workhorse" # gitlab_workhorse['log_directory'] = "/var/log/gitlab/gitlab-workhorse" # gitlab_workhorse['proxy_headers_timeout'] = "1m0s" ##! limit number of concurrent API requests, defaults to 0 which is unlimited # gitlab_workhorse['api_limit'] = 0 ##! limit number of API requests allowed to be queued, defaults to 0 which ##! disables queuing # gitlab_workhorse['api_queue_limit'] = 0 ##! duration after which we timeout requests if they sit too long in the queue # gitlab_workhorse['api_queue_duration'] = "30s" ##! Long polling duration for job requesting for runners # gitlab_workhorse['api_ci_long_polling_duration'] = "60s" ##! Log format: default is text, can also be json or none. # gitlab_workhorse['log_format'] = "json" # gitlab_workhorse['env_directory'] = "/opt/gitlab/etc/gitlab-workhorse/env" # gitlab_workhorse['env'] = { # 'PATH' => "/opt/gitlab/bin:/opt/gitlab/embedded/bin:/bin:/usr/bin", # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } ################################################################################ ## GitLab User Settings ##! Modify default git user. ##! Docs: https://docs.gitlab.com/omnibus/settings/configuration.html#changing-the-name-of-the-git-user-group ################################################################################ # user['username'] = "git" # user['group'] = "git" # user['uid'] = nil # user['gid'] = nil ##! The shell for the git user # user['shell'] = "/bin/sh" ##! The home directory for the git user # user['home'] = "/var/opt/gitlab" # user['git_user_name'] = "GitLab" # user['git_user_email'] = "gitlab@#{node['fqdn']}" ################################################################################ ## GitLab Unicorn ##! Tweak unicorn settings. ##! Docs: https://docs.gitlab.com/omnibus/settings/unicorn.html ################################################################################ # unicorn['enable'] = true # unicorn['worker_timeout'] = 60 ###! Minimum worker_processes is 2 at this moment ###! See https://gitlab.com/gitlab-org/gitlab-foss/issues/18771 # unicorn['worker_processes'] = 2 ### Advanced settings # unicorn['listen'] = 'localhost' # unicorn['port'] = 8080 # unicorn['socket'] = '/var/opt/gitlab/gitlab-rails/sockets/gitlab.socket' # unicorn['pidfile'] = '/opt/gitlab/var/unicorn/unicorn.pid' # unicorn['tcp_nopush'] = true # unicorn['backlog_socket'] = 1024 ###! **Make sure somaxconn is equal or higher then backlog_socket** # unicorn['somaxconn'] = 1024 ###! **We do not recommend changing this setting** # unicorn['log_directory'] = "/var/log/gitlab/unicorn" ### **Only change these settings if you understand well what they mean** ###! Docs: https://docs.gitlab.com/ee/administration/operations/unicorn.html#unicorn-worker-killer ###! https://github.com/kzk/unicorn-worker-killer # unicorn['worker_memory_limit_min'] = "1024 * 1 << 20" # unicorn['worker_memory_limit_max'] = "1280 * 1 << 20" # unicorn['exporter_enabled'] = false # unicorn['exporter_address'] = "127.0.0.1" # unicorn['exporter_port'] = 8083 ################################################################################ ## GitLab Puma ##! Tweak puma settings. You should only use Unicorn or Puma, not both. ##! Docs: https://docs.gitlab.com/omnibus/settings/puma.html ################################################################################ # puma['enable'] = false # puma['ha'] = false # puma['worker_timeout'] = 60 # puma['worker_processes'] = 2 # puma['min_threads'] = 4 # puma['max_threads'] = 4 ### Advanced settings # puma['listen'] = '127.0.0.1' # puma['port'] = 8080 # puma['socket'] = '/var/opt/gitlab/gitlab-rails/sockets/gitlab.socket' # puma['pidfile'] = '/opt/gitlab/var/puma/puma.pid' # puma['state_path'] = '/opt/gitlab/var/puma/puma.state' ###! **We do not recommend changing this setting** # puma['log_directory'] = "/var/log/gitlab/puma" ### **Only change these settings if you understand well what they mean** ###! Docs: https://github.com/schneems/puma_worker_killer # puma['per_worker_max_memory_mb'] = 850 # puma['exporter_enabled'] = false # puma['exporter_address'] = "127.0.0.1" # puma['exporter_port'] = 8083 ################################################################################ ## GitLab Sidekiq ################################################################################ ##! GitLab allows one to start multiple sidekiq processes. These ##! processes can be used to consume a dedicated set of queues. This ##! can be used to ensure certain queues are able to handle additional workload. ##! https://docs.gitlab.com/ee/administration/operations/extra_sidekiq_processes.html # sidekiq['log_directory'] = "/var/log/gitlab/sidekiq" # sidekiq['log_format'] = "json" # sidekiq['shutdown_timeout'] = 4 # sidekiq['cluster'] = true # sidekiq['experimental_queue_selector'] = false # sidekiq['interval'] = nil # sidekiq['max_concurrency'] = 50 # sidekiq['min_concurrency'] = nil ##! Each entry in the queue_groups array denotes a group of queues that have to be processed by a ##! Sidekiq process. Multiple queues can be processed by the same process by ##! separating them with a comma within the group entry, a `*` will process all queues # sidekiq['queue_groups'] = ['*'] ##! If negate is enabled then sidekiq-cluster will process all the queues that ##! don't match those in queue_groups. # sidekiq['negate'] = false # sidekiq['metrics_enabled'] = true # sidekiq['listen_address'] = "localhost" # sidekiq['listen_port'] = 8082 ################################################################################ ## gitlab-shell ################################################################################ # gitlab_shell['audit_usernames'] = false # gitlab_shell['log_level'] = 'INFO' # gitlab_shell['log_format'] = 'json' # gitlab_shell['http_settings'] = { user: 'username', password: 'password', ca_file: '/etc/ssl/cert.pem', ca_path: '/etc/pki/tls/certs', self_signed_cert: false} # gitlab_shell['log_directory'] = "/var/log/gitlab/gitlab-shell/" # gitlab_shell['custom_hooks_dir'] = "/opt/gitlab/embedded/service/gitlab-shell/hooks" # gitlab_shell['auth_file'] = "/var/opt/gitlab/.ssh/authorized_keys" ### Migration to Go feature flags ###! Docs: https://gitlab.com/gitlab-org/gitlab-shell#migration-to-go-feature-flags # gitlab_shell['migration'] = { enabled: true, features: [] } ### Git trace log file. ###! If set, git commands receive GIT_TRACE* environment variables ###! Docs: https://git-scm.com/book/es/v2/Git-Internals-Environment-Variables#Debugging ###! An absolute path starting with / – the trace output will be appended to ###! that file. It needs to exist so we can check permissions and avoid ###! throwing warnings to the users. # gitlab_shell['git_trace_log_file'] = "/var/log/gitlab/gitlab-shell/gitlab-shell-git-trace.log" ##! **We do not recommend changing this directory.** # gitlab_shell['dir'] = "/var/opt/gitlab/gitlab-shell" ################################################################ ## GitLab PostgreSQL ################################################################ ###! Changing any of these settings requires a restart of postgresql. ###! By default, reconfigure reloads postgresql if it is running. If you ###! change any of these settings, be sure to run `gitlab-ctl restart postgresql` ###! after reconfigure in order for the changes to take effect. # postgresql['enable'] = true # postgresql['listen_address'] = nil # postgresql['port'] = 5432 # postgresql['data_dir'] = "/var/opt/gitlab/postgresql/data" ##! **recommend value is 1/4 of total RAM, up to 14GB.** # postgresql['shared_buffers'] = "256MB" ### Advanced settings # postgresql['ha'] = false # postgresql['dir'] = "/var/opt/gitlab/postgresql" # postgresql['log_directory'] = "/var/log/gitlab/postgresql" # postgresql['log_destination'] = nil # postgresql['logging_collector'] = nil # postgresql['log_truncate_on_rotation'] = nil # postgresql['log_rotation_age'] = nil # postgresql['log_rotation_size'] = nil # postgresql['username'] = "gitlab-psql" # postgresql['group'] = "gitlab-psql" ##! `SQL_USER_PASSWORD_HASH` can be generated using the command `gitlab-ctl pg-password-md5 gitlab` # postgresql['sql_user_password'] = 'SQL_USER_PASSWORD_HASH' # postgresql['uid'] = nil # postgresql['gid'] = nil # postgresql['shell'] = "/bin/sh" # postgresql['home'] = "/var/opt/gitlab/postgresql" # postgresql['user_path'] = "/opt/gitlab/embedded/bin:/opt/gitlab/bin:$PATH" # postgresql['sql_user'] = "gitlab" # postgresql['max_connections'] = 200 # postgresql['md5_auth_cidr_addresses'] = [] # postgresql['trust_auth_cidr_addresses'] = [] # postgresql['wal_buffers'] = "-1" # postgresql['autovacuum_max_workers'] = "3" # postgresql['autovacuum_freeze_max_age'] = "200000000" # postgresql['log_statement'] = nil # postgresql['track_activity_query_size'] = "1024" # postgresql['shared_preload_libraries'] = nil # postgresql['dynamic_shared_memory_type'] = nil # postgresql['hot_standby'] = "off" ### SSL settings # See https://www.postgresql.org/docs/11/static/runtime-config-connection.html#GUC-SSL-CERT-FILE for more details # postgresql['ssl'] = 'on' # postgresql['ssl_ciphers'] = 'HIGH:MEDIUM:+3DES:!aNULL:!SSLv3:!TLSv1' # postgresql['ssl_cert_file'] = 'server.crt' # postgresql['ssl_key_file'] = 'server.key' # postgresql['ssl_ca_file'] = '/opt/gitlab/embedded/ssl/certs/cacert.pem' # postgresql['ssl_crl_file'] = nil ### Replication settings ###! Note, some replication settings do not require a full restart. They are documented below. # postgresql['wal_level'] = "hot_standby" # postgresql['max_wal_senders'] = 5 # postgresql['max_replication_slots'] = 0 # postgresql['max_locks_per_transaction'] = 128 # Backup/Archive settings # postgresql['archive_mode'] = "off" ###! Changing any of these settings only requires a reload of postgresql. You do not need to ###! restart postgresql if you change any of these and run reconfigure. # postgresql['work_mem'] = "16MB" # postgresql['maintenance_work_mem'] = "16MB" # postgresql['checkpoint_segments'] = 10 # postgresql['checkpoint_timeout'] = "5min" # postgresql['checkpoint_completion_target'] = 0.9 # postgresql['effective_io_concurrency'] = 1 # postgresql['checkpoint_warning'] = "30s" # postgresql['effective_cache_size'] = "1MB" # postgresql['shmmax'] = 17179869184 # or 4294967295 # postgresql['shmall'] = 4194304 # or 1048575 # postgresql['autovacuum'] = "on" # postgresql['log_autovacuum_min_duration'] = "-1" # postgresql['autovacuum_naptime'] = "1min" # postgresql['autovacuum_vacuum_threshold'] = "50" # postgresql['autovacuum_analyze_threshold'] = "50" # postgresql['autovacuum_vacuum_scale_factor'] = "0.02" # postgresql['autovacuum_analyze_scale_factor'] = "0.01" # postgresql['autovacuum_vacuum_cost_delay'] = "20ms" # postgresql['autovacuum_vacuum_cost_limit'] = "-1" # postgresql['statement_timeout'] = "60000" # postgresql['idle_in_transaction_session_timeout'] = "60000" # postgresql['log_line_prefix'] = "%a" # postgresql['max_worker_processes'] = 8 # postgresql['max_parallel_workers_per_gather'] = 0 # postgresql['log_lock_waits'] = 1 # postgresql['deadlock_timeout'] = '5s' # postgresql['track_io_timing'] = 0 # postgresql['default_statistics_target'] = 1000 ### Available in PostgreSQL 9.6 and later # postgresql['min_wal_size'] = 80MB # postgresql['max_wal_size'] = 1GB # Backup/Archive settings # postgresql['archive_command'] = nil # postgresql['archive_timeout'] = "0" ### Replication settings # postgresql['sql_replication_user'] = "gitlab_replicator" # postgresql['sql_replication_password'] = "md5 hash of postgresql password" # You can generate with `gitlab-ctl pg-password-md5 <dbuser>` # postgresql['wal_keep_segments'] = 10 # postgresql['max_standby_archive_delay'] = "30s" # postgresql['max_standby_streaming_delay'] = "30s" # postgresql['synchronous_commit'] = on # postgresql['synchronous_standby_names'] = '' # postgresql['hot_standby_feedback'] = 'off' # postgresql['random_page_cost'] = 2.0 # postgresql['log_temp_files'] = -1 # postgresql['log_checkpoints'] = 'off' # To add custom entries to pg_hba.conf use the following # postgresql['custom_pg_hba_entries'] = { # APPLICATION: [ # APPLICATION should identify what the settings are used for # { # type: example, # database: example, # user: example, # cidr: example, # method: example, # option: example # } # ] # } # See https://www.postgresql.org/docs/11/static/auth-pg-hba-conf.html for an explanation # of the values ### Version settings # Set this if you have disabled the bundled PostgreSQL but still want to use the backup rake tasks # postgresql['version'] = 10 ################################################################################ ## GitLab Redis ##! **Can be disabled if you are using your own Redis instance.** ##! Docs: https://docs.gitlab.com/omnibus/settings/redis.html ################################################################################ # redis['enable'] = true # redis['ha'] = false # redis['hz'] = 10 # redis['dir'] = "/var/opt/gitlab/redis" # redis['log_directory'] = "/var/log/gitlab/redis" # redis['username'] = "gitlab-redis" # redis['group'] = "gitlab-redis" # redis['maxclients'] = "10000" # redis['maxmemory'] = "0" # redis['maxmemory_policy'] = "noeviction" # redis['maxmemory_samples'] = "5" # redis['tcp_backlog'] = 511 # redis['tcp_timeout'] = "60" # redis['tcp_keepalive'] = "300" # redis['uid'] = nil # redis['gid'] = nil ### Disable or obfuscate unnecessary redis command names ### Uncomment and edit this block to add or remove entries. ### See https://docs.gitlab.com/omnibus/settings/redis.html#renamed-commands ### for detailed usage ### # redis['rename_commands'] = { # 'KEYS': '' #} # ###! **To enable only Redis service in this machine, uncomment ###! one of the lines below (choose master or replica instance types).** ###! Docs: https://docs.gitlab.com/omnibus/settings/redis.html ###! https://docs.gitlab.com/ee/administration/high_availability/redis.html # redis_master_role['enable'] = true # redis_replica_role['enable'] = true ### Redis TCP support (will disable UNIX socket transport) # redis['bind'] = '0.0.0.0' # or specify an IP to bind to a single one # redis['port'] = 6379 # redis['password'] = 'redis-password-goes-here' ### Redis Sentinel support ###! **You need a master replica Redis replication to be able to do failover** ###! **Please read the documentation before enabling it to understand the ###! caveats:** ###! Docs: https://docs.gitlab.com/ee/administration/high_availability/redis.html ### Replication support #### Replica Redis instance # redis['master'] = false # by default this is true #### Replica and Sentinel shared configuration ####! **Both need to point to the master Redis instance to get replication and ####! heartbeat monitoring** # redis['master_name'] = 'gitlab-redis' # redis['master_ip'] = nil # redis['master_port'] = 6379 #### Support to run redis replicas in a Docker or NAT environment ####! Docs: https://redis.io/topics/replication#configuring-replication-in-docker-and-nat # redis['announce_ip'] = nil # redis['announce_port'] = nil ####! **Master password should have the same value defined in ####! redis['password'] to enable the instance to transition to/from ####! master/replica in a failover event.** # redis['master_password'] = 'redis-password-goes-here' ####! Increase these values when your replicas can't catch up with master # redis['client_output_buffer_limit_normal'] = '0 0 0' # redis['client_output_buffer_limit_replica'] = '256mb 64mb 60' # redis['client_output_buffer_limit_pubsub'] = '32mb 8mb 60' #####! Redis snapshotting frequency #####! Set to [] to disable #####! Set to [''] to clear previously set values # redis['save'] = [ '900 1', '300 10', '60 10000' ] #####! Redis lazy freeing #####! Defaults to false # redis['lazyfree_lazy_eviction'] = true # redis['lazyfree_lazy_expire'] = true # redis['lazyfree_lazy_server_del'] = true # redis['replica_lazy_flush'] = true ################################################################################ ## GitLab Web server ##! Docs: https://docs.gitlab.com/omnibus/settings/nginx.html#using-a-non-bundled-web-server ################################################################################ ##! When bundled nginx is disabled we need to add the external webserver user to ##! the GitLab webserver group. # web_server['external_users'] = [] # web_server['username'] = 'gitlab-www' # web_server['group'] = 'gitlab-www' # web_server['uid'] = nil # web_server['gid'] = nil # web_server['shell'] = '/bin/false' # web_server['home'] = '/var/opt/gitlab/nginx' ################################################################################ ## GitLab NGINX ##! Docs: https://docs.gitlab.com/omnibus/settings/nginx.html ################################################################################ # nginx['enable'] = true # nginx['client_max_body_size'] = '250m' # nginx['redirect_http_to_https'] = false # nginx['redirect_http_to_https_port'] = 80 ##! Most root CA's are included by default # nginx['ssl_client_certificate'] = "/etc/gitlab/ssl/ca.crt" ##! enable/disable 2-way SSL client authentication # nginx['ssl_verify_client'] = "off" ##! if ssl_verify_client on, verification depth in the client certificates chain # nginx['ssl_verify_depth'] = "1" # nginx['ssl_certificate'] = "/etc/gitlab/ssl/#{node['fqdn']}.crt" # nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/#{node['fqdn']}.key" # nginx['ssl_ciphers'] = "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256" # nginx['ssl_prefer_server_ciphers'] = "on" ##! **Recommended by: https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html ##! https://cipherli.st/** # nginx['ssl_protocols'] = "TLSv1.2 TLSv1.3" ##! **Recommended in: https://nginx.org/en/docs/http/ngx_http_ssl_module.html** # nginx['ssl_session_cache'] = "builtin:1000 shared:SSL:10m" ##! **Default according to https://nginx.org/en/docs/http/ngx_http_ssl_module.html** # nginx['ssl_session_timeout'] = "5m" # nginx['ssl_dhparam'] = nil # Path to dhparams.pem, eg. /etc/gitlab/ssl/dhparams.pem # nginx['listen_addresses'] = ['*', '[::]'] ##! **Defaults to forcing web browsers to always communicate using only HTTPS** ##! Docs: https://docs.gitlab.com/omnibus/settings/nginx.html#setting-http-strict-transport-security # nginx['hsts_max_age'] = 31536000 # nginx['hsts_include_subdomains'] = false ##! Defaults to stripping path information when making cross-origin requests # nginx['referrer_policy'] = 'strict-origin-when-cross-origin' ##! **Docs: http://nginx.org/en/docs/http/ngx_http_gzip_module.html** # nginx['gzip_enabled'] = true ##! **Override only if you use a reverse proxy** ##! Docs: https://docs.gitlab.com/omnibus/settings/nginx.html#setting-the-nginx-listen-port # nginx['listen_port'] = nil ##! **Override only if your reverse proxy internally communicates over HTTP** ##! Docs: https://docs.gitlab.com/omnibus/settings/nginx.html#supporting-proxied-ssl # nginx['listen_https'] = nil # nginx['custom_gitlab_server_config'] = "location ^~ /foo-namespace/bar-project/raw/ {\n deny all;\n}\n" # nginx['custom_nginx_config'] = "include /etc/nginx/conf.d/example.conf;" # nginx['proxy_read_timeout'] = 3600 # nginx['proxy_connect_timeout'] = 300 # nginx['proxy_set_headers'] = { # "Host" => "$http_host_with_default", # "X-Real-IP" => "$remote_addr", # "X-Forwarded-For" => "$proxy_add_x_forwarded_for", # "X-Forwarded-Proto" => "https", # "X-Forwarded-Ssl" => "on", # "Upgrade" => "$http_upgrade", # "Connection" => "$connection_upgrade" # } # nginx['proxy_cache_path'] = 'proxy_cache keys_zone=gitlab:10m max_size=1g levels=1:2' # nginx['proxy_cache'] = 'gitlab' # nginx['http2_enabled'] = true # nginx['real_ip_trusted_addresses'] = [] # nginx['real_ip_header'] = nil # nginx['real_ip_recursive'] = nil # nginx['custom_error_pages'] = { # '404' => { # 'title' => 'Example title', # 'header' => 'Example header', # 'message' => 'Example message' # } # } ### Advanced settings # nginx['dir'] = "/var/opt/gitlab/nginx" # nginx['log_directory'] = "/var/log/gitlab/nginx" # nginx['worker_processes'] = 4 # nginx['worker_connections'] = 10240 # nginx['log_format'] = '$remote_addr - $remote_user [$time_local] "$request_method $filtered_request_uri $server_protocol" $status $body_bytes_sent "$filtered_http_referer" "$http_user_agent" $gzip_ratio' # nginx['sendfile'] = 'on' # nginx['tcp_nopush'] = 'on' # nginx['tcp_nodelay'] = 'on' # nginx['gzip'] = "on" # nginx['gzip_http_version'] = "1.0" # nginx['gzip_comp_level'] = "2" # nginx['gzip_proxied'] = "any" # nginx['gzip_types'] = [ "text/plain", "text/css", "application/x-javascript", "text/xml", "application/xml", "application/xml+rss", "text/javascript", "application/json" ] # nginx['keepalive_timeout'] = 65 # nginx['cache_max_size'] = '5000m' # nginx['server_names_hash_bucket_size'] = 64 ##! These paths have proxy_request_buffering disabled # nginx['request_buffering_off_path_regex'] = "\.git/git-receive-pack$|\.git/info/refs?service=git-receive-pack$|\.git/gitlab-lfs/objects|\.git/info/lfs/objects/batch$" ### Nginx status # nginx['status'] = { # "enable" => true, # "listen_addresses" => ["127.0.0.1"], # "fqdn" => "dev.example.com", # "port" => 9999, # "vts_enable" => true, # "options" => { # "stub_status" => "on", # Turn on stats # "server_tokens" => "off", # Don't show the version of NGINX # "request_log" => "off", # Disable logs for stats # "allow" => "127.0.0.1", # Only allow access from localhost # "deny" => "all" # Deny access to anyone else # } # } ################################################################################ ## GitLab Logging ##! Docs: https://docs.gitlab.com/omnibus/settings/logs.html ################################################################################ # logging['svlogd_size'] = 200 * 1024 * 1024 # rotate after 200 MB of log data # logging['svlogd_num'] = 30 # keep 30 rotated log files # logging['svlogd_timeout'] = 24 * 60 * 60 # rotate after 24 hours # logging['svlogd_filter'] = "gzip" # compress logs with gzip # logging['svlogd_udp'] = nil # transmit log messages via UDP # logging['svlogd_prefix'] = nil # custom prefix for log messages # logging['logrotate_frequency'] = "daily" # rotate logs daily # logging['logrotate_maxsize'] = nil # rotate logs when they grow bigger than size bytes even before the specified time interval (daily, weekly, monthly, or yearly) # logging['logrotate_size'] = nil # do not rotate by size by default # logging['logrotate_rotate'] = 30 # keep 30 rotated logs # logging['logrotate_compress'] = "compress" # see 'man logrotate' # logging['logrotate_method'] = "copytruncate" # see 'man logrotate' # logging['logrotate_postrotate'] = nil # no postrotate command by default # logging['logrotate_dateformat'] = nil # use date extensions for rotated files rather than numbers e.g. a value of "-%Y-%m-%d" would give rotated files like production.log-2016-03-09.gz ### UDP log forwarding ##! Docs: http://docs.gitlab.com/omnibus/settings/logs.html#udp-log-forwarding ##! remote host to ship log messages to via UDP # logging['udp_log_shipping_host'] = nil ##! override the hostname used when logs are shipped via UDP, ## by default the system hostname will be used. # logging['udp_log_shipping_hostname'] = nil ##! remote port to ship log messages to via UDP # logging['udp_log_shipping_port'] = 514 ################################################################################ ## Logrotate ##! Docs: https://docs.gitlab.com/omnibus/settings/logs.html#logrotate ##! You can disable built in logrotate feature. ################################################################################ # logrotate['enable'] = true # logrotate['log_directory'] = "/var/log/gitlab/logrotate" ################################################################################ ## Users and groups accounts ##! Disable management of users and groups accounts. ##! **Set only if creating accounts manually** ##! Docs: https://docs.gitlab.com/omnibus/settings/configuration.html#disable-user-and-group-account-management ################################################################################ # manage_accounts['enable'] = false ################################################################################ ## Storage directories ##! Disable managing storage directories ##! Docs: https://docs.gitlab.com/omnibus/settings/configuration.html#disable-storage-directories-management ################################################################################ ##! **Set only if the select directories are created manually** # manage_storage_directories['enable'] = false # manage_storage_directories['manage_etc'] = false ################################################################################ ## Runtime directory ##! Docs: https://docs.gitlab.com//omnibus/settings/configuration.html#configuring-runtime-directory ################################################################################ # runtime_dir '/run' ################################################################################ ## Git ##! Advanced setting for configuring git system settings for omnibus-gitlab ##! internal git ################################################################################ ##! For multiple options under one header use array of comma separated values, ##! eg.: ##! { "receive" => ["fsckObjects = true"], "alias" => ["st = status", "co = checkout"] } # omnibus_gitconfig['system'] = { # "pack" => ["threads = 1", "useSparse = true"], # "receive" => ["fsckObjects = true", "advertisePushOptions = true"], # "repack" => ["writeBitmaps = true"], # "transfer" => ["hideRefs=^refs/tmp/", "hideRefs=^refs/keep-around/", "hideRefs=^refs/remotes/"], # "core" => [ # 'alternateRefsCommand="exit 0 #"', # "fsyncObjectFiles = true" # ], # "fetch" => ["writeCommitGraph = true"] # } ################################################################################ ## GitLab Pages ##! Docs: https://docs.gitlab.com/ee/pages/administration.html ################################################################################ ##! Define to enable GitLab Pages # pages_external_url "http://pages.example.com/" # gitlab_pages['enable'] = false ##! Configure to expose GitLab Pages on external IP address, serving the HTTP # gitlab_pages['external_http'] = [] ##! Configure to expose GitLab Pages on external IP address, serving the HTTPS # gitlab_pages['external_https'] = [] ##! Configure to use the default list of cipher suites # gitlab_pages['insecure_ciphers'] = false ##! Configure to enable health check endpoint on GitLab Pages # gitlab_pages['status_uri'] = "/@status" ##! Tune the maximum number of concurrent connections GitLab Pages will handle. ##! This should be in the range 1 - 10000, defaulting to 5000. # gitlab_pages['max_connections'] = 5000 ##! Configure to use JSON structured logging in GitLab Pages # gitlab_pages['log_format'] = "json" ##! Configure verbose logging for GitLab Pages # gitlab_pages['log_verbose'] = false ##! Error Reporting and Logging with Sentry # gitlab_pages['sentry_enabled'] = false # gitlab_pages['sentry_dsn'] = 'https://<key>@sentry.io/<project>' # gitlab_pages['sentry_environment'] = 'production' ##! Listen for requests forwarded by reverse proxy # gitlab_pages['listen_proxy'] = "localhost:8090" ##! Configure GitLab Pages to use an HTTP Proxy # gitlab_pages['http_proxy'] = "http://example:8080" # gitlab_pages['redirect_http'] = true # gitlab_pages['use_http2'] = true # gitlab_pages['dir'] = "/var/opt/gitlab/gitlab-pages" # gitlab_pages['log_directory'] = "/var/log/gitlab/gitlab-pages" # gitlab_pages['artifacts_server'] = true # gitlab_pages['artifacts_server_url'] = nil # Defaults to external_url + '/api/v4' # gitlab_pages['artifacts_server_timeout'] = 10 ##! Environments that do not support bind-mounting should set this parameter to ##! true. This is incompatible with the artifacts server # gitlab_pages['inplace_chroot'] = false ##! Prometheus metrics for Pages docs: https://gitlab.com/gitlab-org/gitlab-pages/#enable-prometheus-metrics # gitlab_pages['metrics_address'] = ":9235" ##! Specifies the minimum SSL/TLS version ("ssl3", "tls1.0", "tls1.1" or "tls1.2") # gitlab_pages['tls_min_version'] = "ssl3" ##! Specifies the maximum SSL/TLS version ("ssl3", "tls1.0", "tls1.1" or "tls1.2") # gitlab_pages['tls_max_version'] = "tls1.2" ##! Pages access control # gitlab_pages['access_control'] = false # gitlab_pages['gitlab_id'] = nil # Automatically generated if not present # gitlab_pages['gitlab_secret'] = nil # Generated if not present # gitlab_pages['auth_redirect_uri'] = nil # Defaults to projects subdomain of pages_external_url and + '/auth' # gitlab_pages['gitlab_server'] = nil # Defaults to external_url # gitlab_pages['internal_gitlab_server'] = nil # defaults to gitlab_server, can be changed to internal load balancer # gitlab_pages['auth_secret'] = nil # Generated if not present ##! GitLab API HTTP client connection timeout # gitlab_pages['gitlab_client_http_timeout'] = "10s" ##! GitLab API JWT Token expiry time" # gitlab_pages['gitlab_client_jwt_expiry'] = "30s" ##! Define custom gitlab-pages HTTP headers for the whole instance # gitlab_pages['headers'] = [] ##! Shared secret used for authentication between Pages and GitLab # gitlab_pages['api_secret_key'] = nil # Will be generated if not set. Base64 encoded and exactly 32 bytes long. ################################################################################ ## GitLab Pages NGINX ################################################################################ # All the settings defined in the "GitLab Nginx" section are also available in # this "GitLab Pages NGINX" section, using the key `pages_nginx`. However, # those settings should be explicitly set. That is, settings given as # `nginx['some_setting']` WILL NOT be automatically replicated as # `pages_nginx['some_setting']` and should be set separately. # Below you can find settings that are exclusive to "GitLab Pages NGINX" # pages_nginx['enable'] = false # gitlab_rails['pages_path'] = "/var/opt/gitlab/gitlab-rails/shared/pages" ################################################################################ ## GitLab CI ##! Docs: https://docs.gitlab.com/ee/ci/quick_start/README.html ################################################################################ # gitlab_ci['gitlab_ci_all_broken_builds'] = true # gitlab_ci['gitlab_ci_add_pusher'] = true # gitlab_ci['builds_directory'] = '/var/opt/gitlab/gitlab-ci/builds' ################################################################################ ## GitLab Mattermost ##! Docs: https://docs.gitlab.com/omnibus/gitlab-mattermost ################################################################################ # mattermost_external_url 'http://mattermost.example.com' # mattermost['enable'] = false # mattermost['username'] = 'mattermost' # mattermost['group'] = 'mattermost' # mattermost['uid'] = nil # mattermost['gid'] = nil # mattermost['home'] = '/var/opt/gitlab/mattermost' # mattermost['database_name'] = 'mattermost_production' # mattermost['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } # mattermost['service_address'] = "127.0.0.1" # mattermost['service_port'] = "8065" # mattermost['service_site_url'] = nil # mattermost['service_allowed_untrusted_internal_connections'] = "" # mattermost['service_enable_api_team_deletion'] = true # mattermost['team_site_name'] = "GitLab Mattermost" # mattermost['sql_driver_name'] = 'mysql' # mattermost['sql_data_source'] = "mmuser:mostest@tcp(dockerhost:3306)/mattermost_test?charset=utf8mb4,utf8" # mattermost['log_file_directory'] = '/var/log/gitlab/mattermost/' # mattermost['gitlab_enable'] = false # mattermost['gitlab_id'] = "12345656" # mattermost['gitlab_secret'] = "123456789" # mattermost['gitlab_scope'] = "" # mattermost['gitlab_auth_endpoint'] = "http://gitlab.example.com/oauth/authorize" # mattermost['gitlab_token_endpoint'] = "http://gitlab.example.com/oauth/token" # mattermost['gitlab_user_api_endpoint'] = "http://gitlab.example.com/api/v4/user" # mattermost['file_directory'] = "/var/opt/gitlab/mattermost/data" # mattermost['plugin_directory'] = "/var/opt/gitlab/mattermost/plugins" # mattermost['plugin_client_directory'] = "/var/opt/gitlab/mattermost/client-plugins" ################################################################################ ## Mattermost NGINX ################################################################################ # All the settings defined in the "GitLab Nginx" section are also available in # this "Mattermost NGINX" section, using the key `mattermost_nginx`. However, # those settings should be explicitly set. That is, settings given as # `nginx['some_setting']` WILL NOT be automatically replicated as # `mattermost_nginx['some_setting']` and should be set separately. # Below you can find settings that are exclusive to "Mattermost NGINX" # mattermost_nginx['enable'] = false # mattermost_nginx['custom_gitlab_mattermost_server_config'] = "location ^~ /foo-namespace/bar-project/raw/ {\n deny all;\n}\n" # mattermost_nginx['proxy_set_headers'] = { # "Host" => "$http_host", # "X-Real-IP" => "$remote_addr", # "X-Forwarded-For" => "$proxy_add_x_forwarded_for", # "X-Frame-Options" => "SAMEORIGIN", # "X-Forwarded-Proto" => "https", # "X-Forwarded-Ssl" => "on", # "Upgrade" => "$http_upgrade", # "Connection" => "$connection_upgrade" # } ################################################################################ ## Registry NGINX ################################################################################ # All the settings defined in the "GitLab Nginx" section are also available in # this "Registry NGINX" section, using the key `registry_nginx`. However, those # settings should be explicitly set. That is, settings given as # `nginx['some_setting']` WILL NOT be automatically replicated as # `registry_nginx['some_setting']` and should be set separately. # Below you can find settings that are exclusive to "Registry NGINX" # registry_nginx['enable'] = false # registry_nginx['proxy_set_headers'] = { # "Host" => "$http_host", # "X-Real-IP" => "$remote_addr", # "X-Forwarded-For" => "$proxy_add_x_forwarded_for", # "X-Forwarded-Proto" => "https", # "X-Forwarded-Ssl" => "on" # } # When the registry is automatically enabled using the same domain as `external_url`, # it listens on this port # registry_nginx['listen_port'] = 5050 ################################################################################ ## Prometheus ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/ ################################################################################ ###! **To enable only Monitoring service in this machine, uncomment ###! the line below.** ###! Docs: https://docs.gitlab.com/ee/administration/high_availability # monitoring_role['enable'] = true # prometheus['enable'] = true # prometheus['monitor_kubernetes'] = true # prometheus['username'] = 'gitlab-prometheus' # prometheus['group'] = 'gitlab-prometheus' # prometheus['uid'] = nil # prometheus['gid'] = nil # prometheus['shell'] = '/bin/sh' # prometheus['home'] = '/var/opt/gitlab/prometheus' # prometheus['log_directory'] = '/var/log/gitlab/prometheus' # prometheus['rules_files'] = ['/var/opt/gitlab/prometheus/rules/*.rules'] # prometheus['scrape_interval'] = 15 # prometheus['scrape_timeout'] = 15 # prometheus['env_directory'] = '/opt/gitlab/etc/prometheus/env' # prometheus['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } # ### Custom scrape configs # # Prometheus can scrape additional jobs via scrape_configs. The default automatically # includes all of the exporters supported by the omnibus config. # # See: https://prometheus.io/docs/operating/configuration/#<scrape_config> # # Example: # # prometheus['scrape_configs'] = [ # { # 'job_name': 'example', # 'static_configs' => [ # 'targets' => ['hostname:port'], # ], # }, # ] # ### Custom alertmanager config # # To configure external alertmanagers, create an alertmanager config. # # See: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#alertmanager_config # # prometheus['alertmanagers'] = [ # { # 'static_configs' => [ # { # 'targets' => [ # 'hostname:port' # ] # } # ] # } # ] # ### Custom Prometheus flags # # prometheus['flags'] = { # 'storage.tsdb.path' => "/var/opt/gitlab/prometheus/data", # 'storage.tsdb.retention.time' => "15d", # 'config.file' => "/var/opt/gitlab/prometheus/prometheus.yml" # } ##! Advanced settings. Should be changed only if absolutely needed. # prometheus['listen_address'] = 'localhost:9090' ################################################################################ ## Prometheus Alertmanager ################################################################################ # alertmanager['enable'] = true # alertmanager['home'] = '/var/opt/gitlab/alertmanager' # alertmanager['log_directory'] = '/var/log/gitlab/alertmanager' # alertmanager['admin_email'] = '[email protected]' # alertmanager['flags'] = { # 'web.listen-address' => "localhost:9093" # 'storage.path' => "/var/opt/gitlab/alertmanager/data" # 'config.file' => "/var/opt/gitlab/alertmanager/alertmanager.yml" # } # alertmanager['env_directory'] = '/opt/gitlab/etc/alertmanager/env' # alertmanager['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } ##! Advanced settings. Should be changed only if absolutely needed. # alertmanager['listen_address'] = 'localhost:9093' # alertmanager['global'] = {} ################################################################################ ## Prometheus Node Exporter ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/node_exporter.html ################################################################################ # node_exporter['enable'] = true # node_exporter['home'] = '/var/opt/gitlab/node-exporter' # node_exporter['log_directory'] = '/var/log/gitlab/node-exporter' # node_exporter['flags'] = { # 'collector.textfile.directory' => "/var/opt/gitlab/node-exporter/textfile_collector" # } # node_exporter['env_directory'] = '/opt/gitlab/etc/node-exporter/env' # node_exporter['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } ##! Advanced settings. Should be changed only if absolutely needed. # node_exporter['listen_address'] = 'localhost:9100' ################################################################################ ## Prometheus Redis exporter ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/redis_exporter.html ################################################################################ # redis_exporter['enable'] = true # redis_exporter['log_directory'] = '/var/log/gitlab/redis-exporter' # redis_exporter['flags'] = { # 'redis.addr' => "unix:///var/opt/gitlab/redis/redis.socket", # } # redis_exporter['env_directory'] = '/opt/gitlab/etc/redis-exporter/env' # redis_exporter['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } ##! Advanced settings. Should be changed only if absolutely needed. # redis_exporter['listen_address'] = 'localhost:9121' ################################################################################ ## Prometheus Postgres exporter ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/postgres_exporter.html ################################################################################ # postgres_exporter['enable'] = true # postgres_exporter['home'] = '/var/opt/gitlab/postgres-exporter' # postgres_exporter['log_directory'] = '/var/log/gitlab/postgres-exporter' # postgres_exporter['flags'] = {} # postgres_exporter['listen_address'] = 'localhost:9187' # postgres_exporter['env_directory'] = '/opt/gitlab/etc/postgres-exporter/env' # postgres_exporter['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } # postgres_exporter['sslmode'] = nil ################################################################################ ## Prometheus PgBouncer exporter (EE only) ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/pgbouncer_exporter.html ################################################################################ # pgbouncer_exporter['enable'] = false # pgbouncer_exporter['log_directory'] = "/var/log/gitlab/pgbouncer-exporter" # pgbouncer_exporter['listen_address'] = 'localhost:9188' # pgbouncer_exporter['env_directory'] = '/opt/gitlab/etc/pgbouncer-exporter/env' # pgbouncer_exporter['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } ################################################################################ ## Prometheus Gitlab exporter ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/gitlab_exporter.html ################################################################################ # gitlab_exporter['enable'] = true # gitlab_exporter['log_directory'] = "/var/log/gitlab/gitlab-exporter" # gitlab_exporter['home'] = "/var/opt/gitlab/gitlab-exporter" ##! Advanced settings. Should be changed only if absolutely needed. # gitlab_exporter['listen_address'] = 'localhost' # gitlab_exporter['listen_port'] = '9168' ##! Manage gitlab-exporter sidekiq probes. false by default when Sentinels are ##! found. # gitlab_exporter['probe_sidekiq'] = true # To completely disable prometheus, and all of it's exporters, set to false # prometheus_monitoring['enable'] = true ################################################################################ ## Grafana Dashboards ##! Docs: https://docs.gitlab.com/ee/administration/monitoring/prometheus/#prometheus-as-a-grafana-data-source ################################################################################ # grafana['enable'] = true # grafana['log_directory'] = '/var/log/gitlab/grafana' # grafana['home'] = '/var/opt/gitlab/grafana' # grafana['admin_password'] = 'admin' # grafana['allow_user_sign_up'] = false # grafana['basic_auth_enabled'] = false # grafana['disable_login_form'] = true # grafana['gitlab_application_id'] = 'GITLAB_APPLICATION_ID' # grafana['gitlab_secret'] = 'GITLAB_SECRET' # grafana['env_directory'] = '/opt/gitlab/etc/grafana/env' # grafana['allowed_groups'] = [] # grafana['gitlab_auth_sign_up'] = true # grafana['env'] = { # 'SSL_CERT_DIR' => "#{node['package']['install-dir']}/embedded/ssl/certs/" # } # grafana['metrics_enabled'] = false # grafana['metrics_basic_auth_username'] = 'grafana_metrics' # default: nil # grafana['metrics_basic_auth_password'] = 'please_set_a_unique_password' # default: nil # grafana['alerting_enabled'] = false ### Dashboards # # See: http://docs.grafana.org/administration/provisioning/#dashboards # # NOTE: Setting this will override the default. # # grafana['dashboards'] = [ # { # 'name' => 'GitLab Omnibus', # 'orgId' => 1, # 'folder' => 'GitLab Omnibus', # 'type' => 'file', # 'disableDeletion' => true, # 'updateIntervalSeconds' => 600, # 'options' => { # 'path' => '/opt/gitlab/embedded/service/grafana-dashboards', # } # } # ] ### Datasources # # See: http://docs.grafana.org/administration/provisioning/#example-datasource-config-file # # NOTE: Setting this will override the default. # # grafana['datasources'] = [ # { # 'name' => 'GitLab Omnibus', # 'type' => 'prometheus', # 'access' => 'proxy', # 'url' => 'http://localhost:9090' # } # ] ##! Advanced settings. Should be changed only if absolutely needed. # grafana['http_addr'] = 'localhost' # grafana['http_port'] = 3000 ################################################################################ ## Gitaly ##! Docs: ################################################################################ # The gitaly['enable'] option exists for the purpose of cluster # deployments, see https://docs.gitlab.com/ee/administration/gitaly/index.html . # gitaly['enable'] = true # gitaly['dir'] = "/var/opt/gitlab/gitaly" # gitaly['log_directory'] = "/var/log/gitlab/gitaly" # gitaly['bin_path'] = "/opt/gitlab/embedded/bin/gitaly" # gitaly['env_directory'] = "/opt/gitlab/etc/gitaly/env" # gitaly['env'] = { # 'PATH' => "/opt/gitlab/bin:/opt/gitlab/embedded/bin:/bin:/usr/bin", # 'HOME' => '/var/opt/gitlab', # 'TZ' => ':/etc/localtime', # 'PYTHONPATH' => "/opt/gitlab/embedded/lib/python3.7/site-packages", # 'ICU_DATA' => "/opt/gitlab/embedded/share/icu/current", # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/", # 'WRAPPER_JSON_LOGGING' => true # } ##! internal_socket_dir is the directory that will contain internal gitaly sockets, ##! separate from socket_path which is the socket that external clients listen on # gitaly['internal_socket_dir'] = "/var/opt/gitlab/gitaly" # gitaly['socket_path'] = "/var/opt/gitlab/gitaly/gitaly.socket" # gitaly['listen_addr'] = "localhost:8075" # gitaly['tls_listen_addr'] = "localhost:9075" # gitaly['certificate_path'] = "/var/opt/gitlab/gitaly/certificate.pem" # gitaly['key_path'] = "/var/opt/gitlab/gitaly/key.pem" # gitaly['prometheus_listen_addr'] = "localhost:9236" # gitaly['logging_level'] = "warn" # gitaly['logging_format'] = "json" # gitaly['logging_sentry_dsn'] = "https://<key>:<secret>@sentry.io/<project>" # gitaly['logging_ruby_sentry_dsn'] = "https://<key>:<secret>@sentry.io/<project>" # gitaly['logging_sentry_environment'] = "production" # gitaly['prometheus_grpc_latency_buckets'] = "[0.001, 0.005, 0.025, 0.1, 0.5, 1.0, 10.0, 30.0, 60.0, 300.0, 1500.0]" # gitaly['auth_token'] = '<secret>' # gitaly['auth_transitioning'] = false # When true, auth is logged to Prometheus but NOT enforced # gitaly['graceful_restart_timeout'] = '1m' # Grace time for a gitaly process to finish ongoing requests # gitaly['git_catfile_cache_size'] = 100 # Number of 'git cat-file' processes kept around for re-use # gitaly['open_files_ulimit'] = 15000 # Maximum number of open files allowed for the gitaly process # gitaly['ruby_max_rss'] = 300000000 # RSS threshold in bytes for triggering a gitaly-ruby restart # gitaly['ruby_graceful_restart_timeout'] = '10m' # Grace time for a gitaly-ruby process to finish ongoing requests # gitaly['ruby_restart_delay'] = '5m' # Period of sustained high RSS that needs to be observed before restarting gitaly-ruby # gitaly['ruby_rugged_git_config_search_path'] = "/opt/gitlab/embedded/etc" # Location of system-wide gitconfig file # gitaly['ruby_num_workers'] = 3 # Number of gitaly-ruby worker processes. Minimum 2, default 2. # gitaly['concurrency'] = [ # { # 'rpc' => "/gitaly.SmartHTTPService/PostReceivePack", # 'max_per_repo' => 20 # }, { # 'rpc' => "/gitaly.SSHService/SSHUploadPack", # 'max_per_repo' => 5 # } # ] ################################################################################ ## Praefect ##! Docs: https://gitlab.com/gitlab-org/gitaly/blob/master/doc/design_ha.md ################################################################################ # praefect['enable'] = false # praefect['dir'] = "/var/opt/gitlab/praefect" # praefect['log_directory'] = "/var/log/gitlab/praefect" # praefect['env_directory'] = "/opt/gitlab/etc/praefect/env" # praefect['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/", # 'GITALY_PID_FILE' => "/var/opt/gitlab/praefect/praefect.pid", # 'WRAPPER_JSON_LOGGING' => true # } # praefect['wrapper_path'] = "/opt/gitlab/embedded/bin/gitaly-wrapper" # praefect['virtual_storage_name'] = "praefect" # praefect['failover_enabled'] = false # praefect['failover_election_strategy'] = 'local' # praefect['auth_token'] = "" # praefect['auth_transitioning'] = false # praefect['listen_addr'] = "localhost:2305" # praefect['postgres_queue_enabled'] = false # praefect['prometheus_listen_addr'] = "localhost:9652" # praefect['prometheus_grpc_latency_buckets'] = "[0.001, 0.005, 0.025, 0.1, 0.5, 1.0, 10.0, 30.0, 60.0, 300.0, 1500.0]" # praefect['logging_level'] = "warn" # praefect['logging_format'] = "json" # praefect['virtual_storages'] = { # 'default' => { # 'praefect-internal-0' => { # 'address' => 'tcp://10.23.56.78:8075', # 'token' => 'abc123' # }, # 'praefect-internal-1' => { # 'address' => 'tcp://10.76.23.31:8075', # 'token' => 'xyz456' # } # }, # 'alternative' => { # 'praefect-internal-2' => { # 'address' => 'tcp://10.34.1.16:8075', # 'token' => 'abc321' # }, # 'praefect-internal-3' => { # 'address' => 'tcp://10.23.18.6:8075', # 'token' => 'xyz890' # } # } # } # praefect['sentry_dsn'] = "https://<key>:<secret>@sentry.io/<project>" # praefect['sentry_environment'] = "production" # praefect['auto_migrate'] = true # praefect['database_host'] = 'postgres.internal' # praefect['database_port'] = 5432 # praefect['database_user'] = 'praefect' # praefect['database_password'] = 'secret' # praefect['database_dbname'] = 'praefect_production' # praefect['database_sslmode'] = 'disable' # praefect['database_sslcert'] = '/path/to/client-cert' # praefect['database_sslkey'] = '/path/to/client-key' # praefect['database_sslrootcert'] = '/path/to/rootcert' ################################################################################ # Storage check ################################################################################ # storage_check['enable'] = false # storage_check['target'] = 'unix:///var/opt/gitlab/gitlab-rails/sockets/gitlab.socket' # storage_check['log_directory'] = '/var/log/gitlab/storage-check' ################################################################################ # Let's Encrypt integration ################################################################################ # letsencrypt['enable'] = nil # letsencrypt['contact_emails'] = [] # This should be an array of email addresses to add as contacts # letsencrypt['group'] = 'root' # letsencrypt['key_size'] = 2048 # letsencrypt['owner'] = 'root' # letsencrypt['wwwroot'] = '/var/opt/gitlab/nginx/www' # See http://docs.gitlab.com/omnibus/settings/ssl.html#automatic-renewal for more on these sesttings # letsencrypt['auto_renew'] = true # letsencrypt['auto_renew_hour'] = 0 # letsencrypt['auto_renew_minute'] = nil # Should be a number or cron expression, if specified. # letsencrypt['auto_renew_day_of_month'] = "*/4" ##! Turn off automatic init system detection. To skip init detection in ##! non-docker containers. Recommended not to change. # package['detect_init'] = true ##! Specify maximum number of tasks that can be created by the systemd unit ##! Will be populated as TasksMax value to the unit file if user is on a systemd ##! version that supports it (>= 227). Will be a no-op if user is not on systemd. # package['systemd_tasks_max'] = 4915 ##! Settings to configure order of GitLab's systemd unit. ##! Note: We do not recommend changing these values unless absolutely necessary # package['systemd_after'] = 'multi-user.target' # package['systemd_wanted_by'] = 'multi-user.target' ################################################################################ ################################################################################ ## Configuration Settings for GitLab EE only ## ################################################################################ ################################################################################ ################################################################################ ## Auxiliary cron jobs applicable to GitLab EE only ################################################################################ # # gitlab_rails['geo_file_download_dispatch_worker_cron'] = "*/10 * * * *" # gitlab_rails['geo_repository_sync_worker_cron'] = "*/5 * * * *" # gitlab_rails['geo_secondary_registry_consistency_worker'] = "* * * * *" # gitlab_rails['geo_prune_event_log_worker_cron'] = "*/5 * * * *" # gitlab_rails['geo_repository_verification_primary_batch_worker_cron'] = "*/5 * * * *" # gitlab_rails['geo_repository_verification_secondary_scheduler_worker_cron'] = "*/5 * * * *" # gitlab_rails['geo_migrated_local_files_clean_up_worker_cron'] = "15 */6 * * *" # gitlab_rails['ldap_sync_worker_cron'] = "30 1 * * *" # gitlab_rails['ldap_group_sync_worker_cron'] = "0 * * * *" # gitlab_rails['historical_data_worker_cron'] = "0 12 * * *" # gitlab_rails['pseudonymizer_worker_cron'] = "0 23 * * *" # gitlab_rails['elastic_index_bulk_cron'] = "*/1 * * * *" ################################################################################ ## Kerberos (EE Only) ##! Docs: https://docs.gitlab.com/ee/integration/kerberos.html#http-git-access ################################################################################ # gitlab_rails['kerberos_enabled'] = true # gitlab_rails['kerberos_keytab'] = /etc/http.keytab # gitlab_rails['kerberos_service_principal_name'] = HTTP/[email protected] # gitlab_rails['kerberos_use_dedicated_port'] = true # gitlab_rails['kerberos_port'] = 8443 # gitlab_rails['kerberos_https'] = true ################################################################################ ## Package repository (EE Only) ##! Docs: https://docs.gitlab.com/ee/administration/maven_packages.md ################################################################################ # gitlab_rails['packages_enabled'] = true # gitlab_rails['packages_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/packages" # gitlab_rails['packages_object_store_enabled'] = false # gitlab_rails['packages_object_store_direct_upload'] = false # gitlab_rails['packages_object_store_background_upload'] = true # gitlab_rails['packages_object_store_proxy_download'] = false # gitlab_rails['packages_object_store_remote_directory'] = "packages" # gitlab_rails['packages_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'host' => 's3.amazonaws.com', # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ################################################################################ ## Dependency proxy (EE Only) ##! Docs: https://docs.gitlab.com/ee/administration/dependency_proxy.md ################################################################################ # gitlab_rails['dependency_proxy_enabled'] = true # gitlab_rails['dependency_proxy_storage_path'] = "/var/opt/gitlab/gitlab-rails/shared/dependency_proxy" # gitlab_rails['dependency_proxy_object_store_enabled'] = false # gitlab_rails['dependency_proxy_object_store_direct_upload'] = false # gitlab_rails['dependency_proxy_object_store_background_upload'] = true # gitlab_rails['dependency_proxy_object_store_proxy_download'] = false # gitlab_rails['dependency_proxy_object_store_remote_directory'] = "dependency_proxy" # gitlab_rails['dependency_proxy_object_store_connection'] = { # 'provider' => 'AWS', # 'region' => 'eu-west-1', # 'aws_access_key_id' => 'AWS_ACCESS_KEY_ID', # 'aws_secret_access_key' => 'AWS_SECRET_ACCESS_KEY', # # # The below options configure an S3 compatible host instead of AWS # # 'host' => 's3.amazonaws.com', # # 'aws_signature_version' => 4, # For creation of signed URLs. Set to 2 if provider does not support v4. # # 'endpoint' => 'https://s3.amazonaws.com', # default: nil - Useful for S3 compliant services such as DigitalOcean Spaces # # 'path_style' => false # Use 'host/bucket_name/object' instead of 'bucket_name.host/object' # } ################################################################################ ## GitLab Sentinel (EE Only) ##! Docs: http://docs.gitlab.com/ce/administration/high_availability/redis.html#high-availability-with-sentinel ################################################################################ ##! **Make sure you configured all redis['master_*'] keys above before ##! continuing.** ##! To enable Sentinel and disable all other services in this machine, ##! uncomment the line below (if you've enabled Redis role, it will keep it). ##! Docs: https://docs.gitlab.com/ee/administration/high_availability/redis.html # redis_sentinel_role['enable'] = true # sentinel['enable'] = true ##! Bind to all interfaces, uncomment to specify an IP and bind to a single one # sentinel['bind'] = '0.0.0.0' ##! Uncomment to change default port # sentinel['port'] = 26379 #### Support to run sentinels in a Docker or NAT environment #####! Docs: https://redis.io/topics/sentinel#sentinel-docker-nat-and-possible-issues # In an standard case, Sentinel will run in the same network service as Redis, so the same IP will be announce for Redis and Sentinel # Only define these values if it is needed to announce for Sentinel a differen IP service than Redis # sentinel['announce_ip'] = nil # If not defined, its value will be taken from redis['announce_ip'] or nil if not present # sentinel['announce_port'] = nil # If not defined, its value will be taken from sentinel['port'] or nil if redis['announce_ip'] not present ##! Quorum must reflect the amount of voting sentinels it take to start a ##! failover. ##! **Value must NOT be greater then the amount of sentinels.** ##! The quorum can be used to tune Sentinel in two ways: ##! 1. If a the quorum is set to a value smaller than the majority of Sentinels ##! we deploy, we are basically making Sentinel more sensible to master ##! failures, triggering a failover as soon as even just a minority of ##! Sentinels is no longer able to talk with the master. ##! 2. If a quorum is set to a value greater than the majority of Sentinels, we ##! are making Sentinel able to failover only when there are a very large ##! number (larger than majority) of well connected Sentinels which agree ##! about the master being down. # sentinel['quorum'] = 1 ### Consider unresponsive server down after x amount of ms. # sentinel['down_after_milliseconds'] = 10000 ### Specifies the failover timeout in milliseconds. ##! It is used in many ways: ##! ##! - The time needed to re-start a failover after a previous failover was ##! already tried against the same master by a given Sentinel, is two ##! times the failover timeout. ##! ##! - The time needed for a replica replicating to a wrong master according ##! to a Sentinel current configuration, to be forced to replicate ##! with the right master, is exactly the failover timeout (counting since ##! the moment a Sentinel detected the misconfiguration). ##! ##! - The time needed to cancel a failover that is already in progress but ##! did not produced any configuration change (REPLICAOF NO ONE yet not ##! acknowledged by the promoted replica). ##! ##! - The maximum time a failover in progress waits for all the replicas to be ##! reconfigured as replicas of the new master. However even after this time ##! the replicas will be reconfigured by the Sentinels anyway, but not with ##! the exact parallel-syncs progression as specified. # sentinel['failover_timeout'] = 60000 ################################################################################ ## Additional Database Settings (EE only) ##! Docs: https://docs.gitlab.com/ee/administration/database_load_balancing.html ################################################################################ # gitlab_rails['db_load_balancing'] = { 'hosts' => ['secondary1.example.com'] } ################################################################################ ## GitLab Geo ##! Docs: https://docs.gitlab.com/ee/gitlab-geo ################################################################################ ##! Geo roles 'geo_primary_role' and 'geo_secondary_role' are set above with ##! other roles. For more information, see: https://docs.gitlab.com/omnibus/roles/README.html#roles. # This is an optional identifier which Geo nodes can use to identify themselves. # For example, if external_url is the same for two secondaries, you must specify # a unique Geo node name for those secondaries. # # If it is blank, it defaults to external_url. # gitlab_rails['geo_node_name'] = nil # gitlab_rails['geo_registry_replication_enabled'] = true # gitlab_rails['geo_registry_replication_primary_api_url'] = 'https://example.com:5000' ################################################################################ ## GitLab Geo Secondary (EE only) ################################################################################ # geo_secondary['auto_migrate'] = true # geo_secondary['db_adapter'] = "postgresql" # geo_secondary['db_encoding'] = "unicode" # geo_secondary['db_collation'] = nil # geo_secondary['db_database'] = "gitlabhq_geo_production" # geo_secondary['db_pool'] = 1 # geo_secondary['db_username'] = "gitlab_geo" # geo_secondary['db_password'] = nil # geo_secondary['db_host'] = "/var/opt/gitlab/geo-postgresql" # geo_secondary['db_port'] = 5431 # geo_secondary['db_socket'] = nil # geo_secondary['db_sslmode'] = nil # geo_secondary['db_sslcompression'] = 0 # geo_secondary['db_sslrootcert'] = nil # geo_secondary['db_sslca'] = nil # geo_secondary['db_fdw'] = true ################################################################################ ## GitLab Geo Secondary Tracking Database (EE only) ################################################################################ # geo_postgresql['enable'] = false # geo_postgresql['ha'] = false # geo_postgresql['dir'] = '/var/opt/gitlab/geo-postgresql' # geo_postgresql['data_dir'] = '/var/opt/gitlab/geo-postgresql/data' # geo_postgresql['pgbouncer_user'] = nil # geo_postgresql['pgbouncer_user_password'] = nil ##! `SQL_USER_PASSWORD_HASH` can be generated using the command `gitlab-ctl pg-password-md5 gitlab` # geo_postgresql['sql_user_password'] = 'SQL_USER_PASSWORD_HASH' ################################################################################ ## Unleash ##! These settings are for GitLab internal use. ##! They are used to control feature flags during GitLab development. ##! Docs: https://docs.gitlab.com/ee/development/feature_flags ################################################################################ # gitlab_rails['feature_flags_unleash_enabled'] = false # gitlab_rails['feature_flags_unleash_url'] = nil # gitlab_rails['feature_flags_unleash_app_name'] = nil # gitlab_rails['feature_flags_unleash_instance_id'] = nil ################################################################################ # Pgbouncer (EE only) # See [GitLab PgBouncer documentation](http://docs.gitlab.com/omnibus/settings/database.html#enabling-pgbouncer-ee-only) # See the [PgBouncer page](https://pgbouncer.github.io/config.html) for details ################################################################################ # pgbouncer['enable'] = false # pgbouncer['log_directory'] = '/var/log/gitlab/pgbouncer' # pgbouncer['data_directory'] = '/var/opt/gitlab/pgbouncer' # pgbouncer['env_directory'] = '/opt/gitlab/etc/pgbouncer/env' # pgbouncer['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } # pgbouncer['listen_addr'] = '0.0.0.0' # pgbouncer['listen_port'] = '6432' # pgbouncer['pool_mode'] = 'transaction' # pgbouncer['server_reset_query'] = 'DISCARD ALL' # pgbouncer['application_name_add_host'] = '1' # pgbouncer['max_client_conn'] = '2048' # pgbouncer['default_pool_size'] = '100' # pgbouncer['min_pool_size'] = '0' # pgbouncer['reserve_pool_size'] = '5' # pgbouncer['reserve_pool_timeout'] = '5.0' # pgbouncer['server_round_robin'] = '0' # pgbouncer['log_connections'] = '0' # pgbouncer['server_idle_timeout'] = '30' # pgbouncer['dns_max_ttl'] = '15.0' # pgbouncer['dns_zone_check_period'] = '0' # pgbouncer['dns_nxdomain_ttl'] = '15.0' # pgbouncer['admin_users'] = %w(gitlab-psql postgres pgbouncer) # pgbouncer['stats_users'] = %w(gitlab-psql postgres pgbouncer) # pgbouncer['ignore_startup_parameters'] = 'extra_float_digits' # pgbouncer['databases'] = { # DATABASE_NAME: { # host: HOSTNAME, # port: PORT # user: USERNAME, # password: PASSWORD ###! generate this with `echo -n '$password + $username' | md5sum` # } # ... # } # pgbouncer['logfile'] = nil # pgbouncer['unix_socket_dir'] = nil # pgbouncer['unix_socket_mode'] = '0777' # pgbouncer['unix_socket_group'] = nil # pgbouncer['auth_type'] = 'md5' # pgbouncer['auth_hba_file'] = nil # pgbouncer['auth_query'] = 'SELECT username, password FROM public.pg_shadow_lookup($1)' # pgbouncer['users'] = { # { # name: USERNAME, # password: MD5_PASSWORD_HASH # } # } # postgresql['pgbouncer_user'] = nil # postgresql['pgbouncer_user_password'] = nil # pgbouncer['server_reset_query_always'] = 0 # pgbouncer['server_check_query'] = 'select 1' # pgbouncer['server_check_delay'] = 30 # pgbouncer['max_db_connections'] = nil # pgbouncer['max_user_connections'] = nil # pgbouncer['syslog'] = 0 # pgbouncer['syslog_facility'] = 'daemon' # pgbouncer['syslog_ident'] = 'pgbouncer' # pgbouncer['log_disconnections'] = 1 # pgbouncer['log_pooler_errors'] = 1 # pgbouncer['stats_period'] = 60 # pgbouncer['verbose'] = 0 # pgbouncer['server_lifetime'] = 3600 # pgbouncer['server_connect_timeout'] = 15 # pgbouncer['server_login_retry'] = 15 # pgbouncer['query_timeout'] = 0 # pgbouncer['query_wait_timeout'] = 120 # pgbouncer['client_idle_timeout'] = 0 # pgbouncer['client_login_timeout'] = 60 # pgbouncer['autodb_idle_timeout'] = 3600 # pgbouncer['suspend_timeout'] = 10 # pgbouncer['idle_transaction_timeout'] = 0 # pgbouncer['pkt_buf'] = 4096 # pgbouncer['listen_backlog'] = 128 # pgbouncer['sbuf_loopcnt'] = 5 # pgbouncer['max_packet_size'] = 2147483647 # pgbouncer['tcp_defer_accept'] = 0 # pgbouncer['tcp_socket_buffer'] = 0 # pgbouncer['tcp_keepalive'] = 1 # pgbouncer['tcp_keepcnt'] = 0 # pgbouncer['tcp_keepidle'] = 0 # pgbouncer['tcp_keepintvl'] = 0 # pgbouncer['disable_pqexec'] = 0 ## Pgbouncer client TLS options # pgbouncer['client_tls_sslmode'] = 'disable' # pgbouncer['client_tls_ca_file'] = nil # pgbouncer['client_tls_key_file'] = nil # pgbouncer['client_tls_cert_file'] = nil # pgbouncer['client_tls_protocols'] = 'all' # pgbouncer['client_tls_dheparams'] = 'auto' # pgbouncer['client_tls_ecdhcurve'] = 'auto' # ## Pgbouncer server TLS options # pgbouncer['server_tls_sslmode'] = 'disable' # pgbouncer['server_tls_ca_file'] = nil # pgbouncer['server_tls_key_file'] = nil # pgbouncer['server_tls_cert_file'] = nil # pgbouncer['server_tls_protocols'] = 'all' # pgbouncer['server_tls_ciphers'] = 'fast' ################################################################################ # Repmgr (EE only) ################################################################################ # repmgr['enable'] = false # repmgr['cluster'] = 'gitlab_cluster' # repmgr['database'] = 'gitlab_repmgr' # repmgr['host'] = nil # repmgr['node_number'] = nil # repmgr['port'] = 5432 # repmgr['trust_auth_cidr_addresses'] = [] # repmgr['username'] = 'gitlab_repmgr' # repmgr['sslmode'] = 'prefer' # repmgr['sslcompression'] = 0 # repmgr['failover'] = 'automatic' # repmgr['log_directory'] = '/var/log/gitlab/repmgrd' # repmgr['node_name'] = nil # repmgr['pg_bindir'] = '/opt/gitlab/embedded/bin' # repmgr['service_start_command'] = '/opt/gitlab/bin/gitlab-ctl start postgresql' # repmgr['service_stop_command'] = '/opt/gitlab/bin/gitlab-ctl stop postgresql' # repmgr['service_reload_command'] = '/opt/gitlab/bin/gitlab-ctl hup postgresql' # repmgr['service_restart_command'] = '/opt/gitlab/bin/gitlab-ctl restart postgresql' # repmgr['service_promote_command'] = nil # repmgr['promote_command'] = '/opt/gitlab/embedded/bin/repmgr standby promote -f /var/opt/gitlab/postgresql/repmgr.conf' # repmgr['follow_command'] = '/opt/gitlab/embedded/bin/repmgr standby follow -f /var/opt/gitlab/postgresql/repmgr.conf' # repmgr['upstream_node'] = nil # repmgr['use_replication_slots'] = false # repmgr['loglevel'] = 'INFO' # repmgr['logfacility'] = 'STDERR' # repmgr['logfile'] = nil # repmgr['event_notification_command'] = nil # repmgr['event_notifications'] = nil # repmgr['rsync_options'] = nil # repmgr['ssh_options'] = nil # repmgr['priority'] = nil # # HA setting to specify if a node should attempt to be master on initialization # repmgr['master_on_initialization'] = true # repmgr['retry_promote_interval_secs'] = 300 # repmgr['witness_repl_nodes_sync_interval_secs'] = 15 # repmgr['reconnect_attempts'] = 6 # repmgr['reconnect_interval'] = 10 # repmgr['monitor_interval_secs'] = 2 # repmgr['master_response_timeout'] = 60 # repmgr['daemon'] = true # repmgrd['enable'] = true ################################################################################ # Consul (EEP only) ################################################################################ # consul['enable'] = false # consul['dir'] = '/var/opt/gitlab/consul' # consul['username'] = 'gitlab-consul' # consul['group'] = 'gitlab-consul' # consul['config_file'] = '/var/opt/gitlab/consul/config.json' # consul['config_dir'] = '/var/opt/gitlab/consul/config.d' # consul['data_dir'] = '/var/opt/gitlab/consul/data' # consul['log_directory'] = '/var/log/gitlab/consul' # consul['env_directory'] = '/opt/gitlab/etc/consul/env' # consul['env'] = { # 'SSL_CERT_DIR' => "/opt/gitlab/embedded/ssl/certs/" # } # consul['monitoring_service_discovery'] = false # consul['node_name'] = nil # consul['script_directory'] = '/var/opt/gitlab/consul/scripts' # consul['configuration'] = { # 'client_addr' => nil, # 'datacenter' => 'gitlab_consul', # 'enable_script_checks' => true, # 'server' => false # } # consul['services'] = [] # consul['service_config'] = { # 'postgresql' => { # 'service' => { # 'name' => "postgresql", # 'address' => '', # 'port' => 5432, # 'checks' => [ # { # 'script' => "/var/opt/gitlab/consul/scripts/check_postgresql", # 'interval' => "10s" # } # ] # } # } # } # consul['watchers'] = { # 'postgresql' => { # enable: false, # handler: 'failover_pgbouncer' # } # } ################################################################################ # Service desk email settings (EEP only) ################################################################################ ### Service desk email ###! Allow users to create new service desk issues by sending an email to ###! service desk address. ###! Docs: https://docs.gitlab.com/ee/administration/reply_by_email.html # gitlab_rails['service_desk_email_enabled'] = false #### Service Desk Mailbox Settings (via `mail_room`) #### Service Desk Email Address ####! The email address including the `%{key}` placeholder that will be replaced ####! to reference the item being replied to. ####! **The placeholder can be omitted but if present, it must appear in the ####! "user" part of the address (before the `@`).** # gitlab_rails['service_desk_email_address'] = "contact_project+%{key}@gmail.com" #### Service Desk Email account username ####! **With third party providers, this is usually the full email address.** ####! **With self-hosted email servers, this is usually the user part of the ####! email address.** # gitlab_rails['service_desk_email_email'] = "[email protected]" #### Service Desk Email account password # gitlab_rails['service_desk_email_password'] = "[REDACTED]" ####! The mailbox where service desk mail will end up. Usually "inbox". # gitlab_rails['service_desk_email_mailbox_name'] = "inbox" ####! The IDLE command timeout. # gitlab_rails['service_desk_email_idle_timeout'] = 60 ####! The file name for internal `mail_room` JSON logfile # gitlab_rails['service_desk_email_log_file'] = "/var/log/gitlab/mailroom/mail_room_json.log" #### Service Desk IMAP Settings # gitlab_rails['service_desk_email_host'] = "imap.gmail.com" # gitlab_rails['service_desk_email_port'] = 993 # gitlab_rails['service_desk_email_ssl'] = true # gitlab_rails['service_desk_email_start_tls'] = false
JSON
hydra/cypress/fixtures/example.json
{ "name": "Using fixtures to represent data", "email": "[email protected]", "body": "Fixtures are a great way to mock data for responses to routes" }
JavaScript
hydra/cypress/helpers/index.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { v4 as uuidv4 } from "uuid" export const prng = () => uuidv4() const isStatusOk = (res) => res.ok ? Promise.resolve(res) : Promise.reject( new Error(`Received unexpected status code ${res.statusCode}`), ) export const findEndUserAuthorization = (subject) => fetch( Cypress.env("admin_url") + "/oauth2/auth/sessions/consent?subject=" + subject, ) .then(isStatusOk) .then((res) => res.json()) export const revokeEndUserAuthorization = (subject) => fetch( Cypress.env("admin_url") + "/oauth2/auth/sessions/consent?subject=" + subject, { method: "DELETE" }, ).then(isStatusOk) export const createClient = (client) => cy .request("POST", Cypress.env("admin_url") + "/clients", client) .then(({ body }) => getClient(body.client_id).then((actual) => { if (actual.client_id !== body.client_id) { return Promise.reject( new Error( `Expected client_id's to match: ${actual.client_id} !== ${body.client}`, ), ) } return body }), ) export const deleteClients = () => cy.request(Cypress.env("admin_url") + "/clients").then(({ body = [] }) => { ;(body || []).forEach(({ client_id }) => deleteClient(client_id)) }) const deleteClient = (client_id) => cy.request("DELETE", Cypress.env("admin_url") + "/clients/" + client_id) const getClient = (id) => cy .request(Cypress.env("admin_url") + "/clients/" + id) .then(({ body }) => body) export const createGrant = (grant) => cy .request( "POST", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", JSON.stringify(grant), ) .then((response) => { const grantID = response.body.id getGrant(grantID).then((actual) => { if (actual.id !== grantID) { return Promise.reject( new Error(`Expected id's to match: ${actual.id} !== ${grantID}`), ) } return Promise.resolve(response) }) }) export const getGrant = (grantID) => cy .request( "GET", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers/" + grantID, ) .then(({ body }) => body) export const deleteGrants = () => cy .request(Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers") .then(({ body = [] }) => { ;(body || []).forEach(({ id }) => deleteGrant(id)) }) const deleteGrant = (id) => cy.request( "DELETE", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers/" + id, )
JavaScript
hydra/cypress/integration/admin/client_create.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { prng } from "../../helpers" describe("The Clients Admin Interface", function () { const nc = () => ({ scope: "foo openid offline_access", grant_types: ["client_credentials"], }) it("should return client_secret with length 26 for newly created clients without client_secret specified", function () { const client = nc() cy.request( "POST", Cypress.env("admin_url") + "/clients", JSON.stringify(client), ).then((response) => { expect(response.body.client_secret.length).to.equal(26) }) }) })
JavaScript
hydra/cypress/integration/admin/grant_jwtbearer.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 const dayjs = require("dayjs") const isBetween = require("dayjs/plugin/isBetween") const utc = require("dayjs/plugin/utc") dayjs.extend(utc) dayjs.extend(isBetween) describe("The JWT-Bearer Grants Admin Interface", () => { let d = dayjs().utc().add(1, "year").set("millisecond", 0) const newGrant = () => ({ issuer: "token-service", subject: "[email protected]", expires_at: d.toISOString(), scope: ["openid", "offline"], jwk: { use: "sig", kty: "RSA", kid: "token-service-key", alg: "RS256", n: "ue1_WT_RU6Lc65dmmD7llh9Tcu_Xc909be1Yr5xlHUpkVzacHhSgjliSjUnGCuMo1-m3ILktgt3p86ba6bmIk9fK3nKA7OztDymHuuaYGbJVHhDSKcCBMXGFPcBLxtEns7nvMoQ-lkFN-kYgfSfg0iPGXeRo2Io7phqr54pBaEG_xMK9c-rQ_G3Y9eXn1JREEgQd4OvA2UR9Vc4E-xAYMx7V-ZOvMeKBj9HACE8cllnpKlEKLMo5O5BvkpqA1MeOtzL5jxUUH8D37TJvVQ67VgTs40dRwWwRePfIMDHRJSeJ0KTpkgnX4fmaF2xfi53N8hM9PHzzCtaWrjzm1r1Gyw", e: "AQAB", }, }) beforeEach(() => { // Clean up all previous grants cy.request( "GET", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", ).then((response) => { response.body.map(({ id }) => { cy.request( "delete", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers/" + id, ).then(() => {}) }) }) }) it("should return newly created jwt-bearer grant and grant can be retrieved later", () => { const grant = newGrant() const start = dayjs().subtract(1, "minutes") const end = dayjs().add(1, "minutes") cy.request( "POST", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", JSON.stringify(grant), ).then((response) => { const createdAt = dayjs(response.body.created_at) const expiresAt = dayjs(response.body.expires_at) const grantID = response.body.id expect(response.body.issuer).to.equal(grant.issuer) expect(response.body.subject).to.equal(grant.subject) expect(createdAt.isBetween(start, end)).to.true expect(expiresAt.isSame(grant.expires_at)).to.true expect(response.body.scope).to.deep.equal(grant.scope) expect(response.body.public_key.set).to.equal(grant.issuer) expect(response.body.public_key.kid).to.equal(grant.jwk.kid) cy.request( "GET", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers/" + grantID, ).then((response) => { expect(response.body.issuer).to.equal(grant.issuer) expect(response.body.subject).to.equal(grant.subject) expect(response.body.scope).to.deep.equal(grant.scope) expect(response.body.public_key.set).to.equal(grant.issuer) expect(response.body.public_key.kid).to.equal(grant.jwk.kid) }) }) }) it("should return newly created jwt-bearer grant in grants list", () => { // We have exactly one grant const grant = newGrant() cy.request( "POST", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", JSON.stringify(grant), ).then(() => {}) cy.request( "GET", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", ).then((response) => { expect(response.body).to.length(1) }) }) it("should fail, because the same grant is already exist", () => { const grant = newGrant() cy.request({ method: "POST", url: Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", failOnStatusCode: false, body: JSON.stringify(grant), }).then((response) => { expect(response.status).to.equal(201) }) cy.request({ method: "POST", url: Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", failOnStatusCode: false, body: JSON.stringify(grant), }).then((response) => { expect(response.status).to.equal(409) }) }) it("should fail, because trying to create grant with no issuer", () => { const grant = newGrant() grant.issuer = "" cy.request({ method: "POST", url: Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", failOnStatusCode: false, body: JSON.stringify(grant), }).then((response) => { expect(response.status).to.equal(400) }) }) it("should fail, because trying to create grant with no subject and no allow_any_subject flag", () => { const grant = newGrant() delete grant.subject delete grant.allow_any_subject cy.request({ method: "POST", url: Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", failOnStatusCode: false, body: JSON.stringify(grant), }).then((response) => { expect(response.status).to.equal(400) }) }) it("should return newly created jwt-bearer grant when issuer is allowed to authorize any subject", () => { const grant = newGrant() delete grant.subject grant.allow_any_subject = true const start = dayjs().subtract(1, "minutes") const end = dayjs().add(1, "minutes") cy.request( "POST", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers", JSON.stringify(grant), ).then((response) => { const createdAt = dayjs(response.body.created_at) const expiresAt = dayjs(response.body.expires_at) const grantID = response.body.id expect(response.body.allow_any_subject).to.equal(grant.allow_any_subject) expect(response.body.issuer).to.equal(grant.issuer) expect(createdAt.isBetween(start, end)).to.true expect(expiresAt.isSame(grant.expires_at)).to.true expect(response.body.scope).to.deep.equal(grant.scope) expect(response.body.public_key.set).to.equal(grant.issuer) expect(response.body.public_key.kid).to.equal(grant.jwk.kid) cy.request( "GET", Cypress.env("admin_url") + "/trust/grants/jwt-bearer/issuers/" + grantID, ).then((response) => { expect(response.body.allow_any_subject).to.equal( grant.allow_any_subject, ) expect(response.body.issuer).to.equal(grant.issuer) expect(response.body.scope).to.deep.equal(grant.scope) expect(response.body.public_key.set).to.equal(grant.issuer) expect(response.body.public_key.kid).to.equal(grant.jwk.kid) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/authorize_code.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("The OAuth 2.0 Authorization Code Grant", function () { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = (extradata) => ({ client_secret: prng(), scope: "offline_access openid", subject_type: "public", token_endpoint_auth_method: "client_secret_basic", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, ...extradata, }) it("should return an Access, Refresh, and ID Token when scope offline_access and openid are granted", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["offline_access", "openid"] }, }) cy.get("body") .invoke("text") .then((content) => { const { result, token: { access_token, id_token, refresh_token }, } = JSON.parse(content) expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.not.be.empty expect(refresh_token).to.not.be.empty }) }) it("should return an Access and Refresh Token when scope offline_access is granted", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["offline_access"] } }) cy.get("body") .invoke("text") .then((content) => { const { result, token: { access_token, id_token, refresh_token }, } = JSON.parse(content) expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.be.undefined expect(refresh_token).to.not.be.empty }) }) it("should return an Access and ID Token when scope offline_access is granted", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["openid"] } }) cy.get("body") .invoke("text") .then((content) => { const { result, token: { access_token, id_token, refresh_token }, } = JSON.parse(content) expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.not.be.empty expect(refresh_token).to.be.undefined }) }) it("should return an Access Token when no scope is granted", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: [] } }) cy.get("body") .invoke("text") .then((content) => { const { result, token: { access_token, id_token, refresh_token }, } = JSON.parse(content) expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.be.undefined expect(refresh_token).to.be.undefined }) }) it("should skip consent if the client is confgured thus", function () { const client = nc({ skip_consent: true }) cy.authCodeFlow(client, { consent: { scope: ["offline_access", "openid"], skip: true }, }) cy.get("body") .invoke("text") .then((content) => { const { result, token: { access_token, id_token, refresh_token }, } = JSON.parse(content) expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.not.be.empty expect(refresh_token).to.not.be.empty }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/authorize_error.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, prng } from "../../helpers" import qs from "querystring" const accessTokenStrategies = ["opaque", "jwt"] describe("OAuth 2.0 Authorization Endpoint Error Handling", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { describe("rejecting login and consent requests", () => { const nc = () => ({ client_secret: prng(), scope: "offline_access openid", subject_type: "public", token_endpoint_auth_method: "client_secret_basic", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should return an error when rejecting login", function () { const client = nc() cy.authCodeFlow(client, { login: { accept: false }, consent: { skip: true }, createClient: true, }) cy.get("body") .invoke("text") .then((content) => { const { result, error_description, token: { access_token, id_token, refresh_token } = {}, } = JSON.parse(content) expect(result).to.equal("error") expect(error_description).to.equal( "The resource owner denied the request", ) expect(access_token).to.be.undefined expect(id_token).to.be.undefined expect(refresh_token).to.be.undefined }) }) it("should return an error when rejecting consent", function () { const client = nc() cy.authCodeFlow(client, { consent: { accept: false }, createClient: true, }) cy.get("body") .invoke("text") .then((content) => { const { result, error_description, token: { access_token, id_token, refresh_token } = {}, } = JSON.parse(content) expect(result).to.equal("error") expect(error_description).to.equal( "The resource owner denied the request", ) expect(access_token).to.be.undefined expect(id_token).to.be.undefined expect(refresh_token).to.be.undefined }) }) }) it("should return an error when an OAuth 2.0 Client ID is used that does not exist", () => { cy.visit( `${Cypress.env( "client_url", )}/oauth2/code?client_id=i-do-not-exist&client_secret=i-am-not-correct}`, { failOnStatusCode: false }, ) cy.location().should(({ search, port }) => { const query = qs.parse(search.substr(1)) expect(query.error).to.equal("invalid_client") // Should show Ory Hydra's Error URL because a redirect URL could not be determined expect(port).to.equal(Cypress.env("public_port")) }) }) it("should return an error when an OAuth 2.0 Client requests a scope that is not allowed to be requested", () => { createClient({ client_secret: prng(), scope: "foo", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code"], }).then((c) => { cy.visit( `${Cypress.env("client_url")}/oauth2/code?client_id=${ c.client_id }&client_secret=${c.client_secret}&scope=bar`, { failOnStatusCode: false }, ) cy.location().should(({ search, port }) => { const query = qs.parse(search.substr(1)) expect(query.error).to.equal("invalid_scope") // This is a client error so we expect the client app to show the error expect(port).to.equal(Cypress.env("client_port")) }) }) }) it("should return an error when an OAuth 2.0 Client requests a response type it is not allowed to call", () => { createClient({ client_secret: prng(), redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], response_types: ["token"], // disallows Authorization Code Grant }).then((c) => { cy.visit( `${Cypress.env("client_url")}/oauth2/code?client_id=${ c.client_id }&client_secret=${c.client_secret}`, { failOnStatusCode: false }, ) cy.get("body").should("contain", "unsupported_response_type") }) }) it("should return an error when an OAuth 2.0 Client requests a grant type it is not allowed to call", () => { createClient({ client_secret: prng(), redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["client_credentials"], }).then((c) => { cy.visit( `${Cypress.env("client_url")}/oauth2/code?client_id=${ c.client_id }&client_secret=${c.client_secret}&scope=`, { failOnStatusCode: false }, ) cy.get("#email").type("[email protected]", { delay: 1 }) cy.get("#password").type("foobar", { delay: 1 }) cy.get("#accept").click() cy.get("#accept").click() cy.get("body").should("contain", "unauthorized_client") }) it("should return an error when an OAuth 2.0 Client requests a redirect_uri that is not preregistered", () => { const c = { client_secret: prng(), redirect_uris: ["http://some-other-domain/not-callback"], grant_types: ["client_credentials"], } createClient(c) cy.visit( `${Cypress.env("client_url")}/oauth2/code?client_id=${ c.client_id }&client_secret=${c.client_secret}&scope=`, { failOnStatusCode: false }, ) cy.location().should(({ search, port }) => { const query = qs.parse(search.substr(1)) console.log(query) expect(query.error).to.equal("invalid_request") expect(query.error_description).to.contain("redirect_uri") // Should show Ory Hydra's Error URL because a redirect URL could not be determined expect(port).to.equal(Cypress.env("public_port")) }) }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/client_creds.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("The OAuth 2.0 Authorization Code Grant", function () { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "foo openid offline_access", grant_types: ["client_credentials"], access_token_strategy: accessTokenStrategy, }) it("should return an Access Token but not Refresh or ID Token for client_credentials flow", function () { createClient(nc()).then((client) => { cy.request( `${Cypress.env("client_url")}/oauth2/cc?client_id=${ client.client_id }&client_secret=${client.client_secret}&scope=${client.scope}`, { failOnStatusCode: false }, ) .its("body") .then((body) => { const { result, token: { access_token, id_token, refresh_token } = {}, } = body expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.be.undefined expect(refresh_token).to.be.undefined }) }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/consent.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("OAuth 2.0 End-User Authorization", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "offline_access", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) const hasConsent = (client, body) => { let found = false body.forEach( ({ consent_request: { client: { client_id }, }, }) => { if (client_id === client.client_id) { found = true } }, ) return found } it("should check if end user authorization exists", () => { createClient(nc()).then((client) => { cy.authCodeFlow(client, { consent: { scope: ["offline_access"], remember: true, }, createClient: false, }) console.log("got ", { client }) cy.request( Cypress.env("admin_url") + "/oauth2/auth/sessions/[email protected]", ) .its("body") .then((body) => { expect(body.length).to.be.greaterThan(0) console.log({ body, client, }) expect(hasConsent(client, body)).to.be.true body.forEach((consent) => { expect( consent.handled_at.match( /^[2-9]\d{3}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/, ), ).not.to.be.empty }) }) cy.request( "DELETE", Cypress.env("admin_url") + "/oauth2/auth/sessions/[email protected]&all=true", ) cy.request( Cypress.env("admin_url") + "/oauth2/auth/sessions/[email protected]", ) .its("body") .then((body) => { expect(body.length).to.eq(0) expect(hasConsent(client, body)).to.be.false }) cy.request(`${Cypress.env("client_url")}/oauth2/introspect/at`) .its("body") .then((body) => { expect(body.result).to.equal("success") expect(body.body.active).to.be.false }) cy.request(`${Cypress.env("client_url")}/oauth2/introspect/rt`) .its("body") .then((body) => { expect(body.result).to.equal("success") expect(body.body.active).to.be.false }) }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/grant_jwtbearer.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, createGrant, deleteClients, deleteGrants, prng, } from "../../helpers" const dayjs = require("dayjs") const isBetween = require("dayjs/plugin/isBetween") const utc = require("dayjs/plugin/utc") dayjs.extend(utc) dayjs.extend(isBetween) const jwt = require("jsonwebtoken") let testPublicJwk let testPrivatePem let invalidtestPrivatePem const initTestKeyPairs = async () => { const algorithm = { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", } const keys = await crypto.subtle.generateKey(algorithm, true, [ "sign", "verify", ]) // public key to jwk const publicJwk = await crypto.subtle.exportKey("jwk", keys.publicKey) publicJwk.kid = "token-service-key" // private key to pem const exportedPK = await crypto.subtle.exportKey("pkcs8", keys.privateKey) const exportedAsBase64 = Buffer.from(exportedPK).toString("base64") const privatePem = `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----` // create another private key to test invalid signatures const invalidKeys = await crypto.subtle.generateKey(algorithm, true, [ "sign", "verify", ]) const invalidPK = await crypto.subtle.exportKey( "pkcs8", invalidKeys.privateKey, ) const invalidAsBase64 = Buffer.from(invalidPK).toString("base64") const invalidPrivatePem = `-----BEGIN PRIVATE KEY-----\n${invalidAsBase64}\n-----END PRIVATE KEY-----` testPublicJwk = publicJwk testPrivatePem = privatePem invalidtestPrivatePem = invalidPrivatePem } const accessTokenStrategies = ["opaque", "jwt"] accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { describe("The OAuth 2.0 JWT Bearer (RFC 7523) Grant", function () { beforeEach(() => { deleteGrants() deleteClients() }) before(() => { return cy.wrap(initTestKeyPairs()) }) const tokenUrl = `${Cypress.env("public_url")}/oauth2/token` const nc = () => ({ client_secret: prng(), scope: "foo openid offline_access", grant_types: ["urn:ietf:params:oauth:grant-type:jwt-bearer"], token_endpoint_auth_method: "client_secret_post", response_types: ["token"], access_token_strategy: accessTokenStrategy, }) const gr = (subject) => ({ issuer: prng(), subject: subject, allow_any_subject: subject === "", scope: ["foo", "openid", "offline_access"], jwk: testPublicJwk, expires_at: dayjs() .utc() .add(1, "year") .set("millisecond", 0) .toISOString(), }) const jwtAssertion = (grant, override) => { const assert = { jti: prng(), iss: grant.issuer, sub: grant.subject, aud: tokenUrl, exp: dayjs().utc().add(2, "minute").set("millisecond", 0).unix(), iat: dayjs().utc().subtract(2, "minute").set("millisecond", 0).unix(), } return { ...assert, ...override } } it("should return an Access Token when given client credentials and a signed JWT assertion", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign(jwtAssertion(grant), testPrivatePem, { algorithm: "RS256", }) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, }) .its("body") .then((body) => { const { access_token, expires_in, scope, token_type } = body expect(access_token).to.not.be.empty expect(expires_in).to.not.be.undefined expect(scope).to.not.be.empty expect(token_type).to.not.be.empty }) }) }) it("should return an Error (400) when not given client credentials", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign(jwtAssertion(grant), testPrivatePem, { algorithm: "RS256", }) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion without a jti", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) var ja = jwtAssertion(grant) delete ja["jti"] const assertion = jwt.sign(ja, testPrivatePem, { algorithm: "RS256" }) // first token request should work fine cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with a duplicated jti", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const jwt1 = jwtAssertion(grant) const assertion1 = jwt.sign(jwt1, testPrivatePem, { algorithm: "RS256", }) // first token request should work fine cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion1, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, }) .its("body") .then((body) => { const { access_token, expires_in, scope, token_type } = body expect(access_token).to.not.be.empty expect(expires_in).to.not.be.undefined expect(scope).to.not.be.empty expect(token_type).to.not.be.empty }) const assertion2 = jwt.sign( jwtAssertion(grant, { jti: jwt1["jti"] }), testPrivatePem, { algorithm: "RS256" }, ) // the second should fail cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion2, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion without an iat", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) var ja = jwtAssertion(grant) delete ja["iat"] const assertion = jwt.sign(ja, testPrivatePem, { algorithm: "RS256", noTimestamp: true, }) // first token request should work fine cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with an invalid signature", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant), invalidtestPrivatePem, { algorithm: "RS256", }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with an invalid subject", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { sub: "invalid_subject" }), testPrivatePem, { algorithm: "RS256" }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Access Token when given client credentials and a JWT assertion with any subject", function () { createClient(nc()).then((client) => { const grant = gr("") // allow any subject createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { sub: "any-subject-is-valid" }), testPrivatePem, { algorithm: "RS256", }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, }) .its("body") .then((body) => { const { access_token, expires_in, scope, token_type } = body expect(access_token).to.not.be.empty expect(expires_in).to.not.be.undefined expect(scope).to.not.be.empty expect(token_type).to.not.be.empty }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with an invalid issuer", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { iss: "invalid_issuer" }), testPrivatePem, { algorithm: "RS256" }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with an invalid audience", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { aud: "invalid_audience" }), testPrivatePem, { algorithm: "RS256" }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with an expired date", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { exp: dayjs() .utc() .subtract(1, "minute") .set("millisecond", 0) .unix(), }), testPrivatePem, { algorithm: "RS256" }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Error (400) when given client credentials and a JWT assertion with a nbf that is still not valid", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { nbf: dayjs().utc().add(1, "minute").set("millisecond", 0).unix(), }), testPrivatePem, { algorithm: "RS256" }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, failOnStatusCode: false, }) .its("status") .then((status) => { expect(status).to.be.equal(400) }) }) }) it("should return an Access Token when given client credentials and a JWT assertion with a nbf that is valid", function () { createClient(nc()).then((client) => { const grant = gr(prng()) createGrant(grant) const assertion = jwt.sign( jwtAssertion(grant, { nbf: dayjs() .utc() .subtract(1, "minute") .set("millisecond", 0) .unix(), }), testPrivatePem, { algorithm: "RS256" }, ) cy.request({ method: "POST", url: tokenUrl, form: true, body: { grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, scope: client.scope, client_secret: client.client_secret, client_id: client.client_id, }, }) .its("body") .then((body) => { const { access_token, expires_in, scope, token_type } = body expect(access_token).to.not.be.empty expect(expires_in).to.not.be.undefined expect(scope).to.not.be.empty expect(token_type).to.not.be.empty }) }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/introspect.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("OpenID Connect Token Introspection", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "offline_access", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should introspect access token", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["offline_access"], createClient: true, }, }) cy.get("body") .invoke("text") .then((content) => { const { result } = JSON.parse(content) expect(result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/oauth2/introspect/at`) .its("body") .then((body) => { expect(body.result).to.equal("success") expect(body.body.active).to.be.true expect(body.body.sub).to.be.equal("[email protected]") expect(body.body.token_type).to.be.equal("Bearer") expect(body.body.token_use).to.be.equal("access_token") }) }) it("should introspect refresh token", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["offline_access"], createClient: true, }, }) cy.get("body") .invoke("text") .then((content) => { const { result } = JSON.parse(content) expect(result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/oauth2/introspect/rt`) .its("body") .then((body) => { expect(body.result).to.equal("success") expect(body.body.active).to.be.true expect(body.body.sub).to.be.equal("[email protected]") expect(body.body.token_type).to.be.equal("Bearer") expect(body.body.token_use).to.be.equal("refresh_token") }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/jwt.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("OAuth 2.0 JSON Web Token Access Tokens", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { before(function () { // this must be a function otherwise this.skip() fails because the context is wrong if ( accessTokenStrategy === "opaque" || (Cypress.env("jwt_enabled") !== "true" && !Boolean(Cypress.env("jwt_enabled"))) ) { this.skip() } }) const nc = () => ({ client_secret: prng(), scope: "offline_access", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should return an Access Token in JWT format and validate it and a Refresh Token in opaque format", () => { createClient(nc()).then((client) => { cy.authCodeFlow(client, { consent: { scope: ["offline_access"], createClient: true }, createClient: false, }) cy.request(`${Cypress.env("client_url")}/oauth2/refresh`) .its("body") .then((body) => { const { result, token } = body expect(result).to.equal("success") expect(token.access_token).to.not.be.empty expect(token.refresh_token).to.not.be.empty expect(token.access_token.split(".").length).to.equal(3) expect(token.refresh_token.split(".").length).to.equal(2) }) cy.request(`${Cypress.env("client_url")}/oauth2/validate-jwt`) .its("body") .then((body) => { console.log(body) expect(body.sub).to.eq("[email protected]") expect(body.client_id).to.eq(client.client_id) expect(body.jti).to.not.be.empty }) }) }) }) }) })
JavaScript
hydra/cypress/integration/oauth2/refresh_token.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("The OAuth 2.0 Refresh Token Grant", function () { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "offline_access openid", redirect_uris: [`${Cypress.env("client_url")}/oauth2/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should return an Access and Refresh Token and refresh the Access Token", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["offline_access"], createClient: true, }, }) cy.request(`${Cypress.env("client_url")}/oauth2/refresh`) .its("body") .then((body) => { const { result, token } = body expect(result).to.equal("success") expect(token.access_token).to.not.be.empty expect(token.refresh_token).to.not.be.empty }) }) it("should return an Access, ID, and Refresh Token and refresh the Access Token and ID Token", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["offline_access", "openid"], createClient: true, }, }) cy.request(`${Cypress.env("client_url")}/oauth2/refresh`) .its("body") .then((body) => { const { result, token } = body expect(result).to.equal("success") expect(token.access_token).to.not.be.empty expect(token.id_token).to.not.be.empty expect(token.refresh_token).to.not.be.empty }) }) it("should revoke Refresh Token on reuse", function () { const referrer = `${Cypress.env("client_url")}/empty` cy.visit(referrer, { failOnStatusCode: false, }) createClient({ scope: "offline_access", redirect_uris: [referrer], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", }).then((client) => { cy.authCodeFlowBrowser(client, { consent: { scope: ["offline_access"] }, createClient: false, }).then((originalResponse) => { expect(originalResponse.status).to.eq(200) expect(originalResponse.body.refresh_token).to.not.be.empty const originalToken = originalResponse.body.refresh_token cy.refreshTokenBrowser(client, originalToken).then( (refreshedResponse) => { expect(refreshedResponse.status).to.eq(200) expect(refreshedResponse.body.refresh_token).to.not.be.empty const refreshedToken = refreshedResponse.body.refresh_token return cy .refreshTokenBrowser(client, originalToken) .then((response) => { expect(response.status).to.eq(401) expect(response.body.error).to.eq("token_inactive") }) .then(() => cy.refreshTokenBrowser(client, refreshedToken)) .then((response) => { expect(response.status).to.eq(401) expect(response.body.error).to.eq("token_inactive") }) }, ) }) }) }) }) }) })
JavaScript
hydra/cypress/integration/openid/authorize_code.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("OpenID Connect Authorize Code Grant", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "openid", subject_type: "public", token_endpoint_auth_method: "client_secret_basic", redirect_uris: [`${Cypress.env("client_url")}/openid/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should return an access, refresh, and ID token", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["openid"] } }, "openid") cy.get("body") .invoke("text") .then((content) => { const { result, token: { access_token, id_token, refresh_token }, claims: { sub, sid }, } = JSON.parse(content) expect(result).to.equal("success") expect(access_token).to.not.be.empty expect(id_token).to.not.be.empty expect(refresh_token).to.be.undefined expect(sub).to.eq("[email protected]") expect(sid).to.not.be.empty }) }) }) }) })
JavaScript
hydra/cypress/integration/openid/dynamic_client_registration.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 describe("OAuth2 / OpenID Connect Dynamic Client Registration", function () { it("should return same client_secret given in request for newly created clients with client_secret specified", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { client_name: "clientName", scope: "foo openid offline_access", grant_types: ["client_credentials"], }, }).then((response) => { expect(response.body.registration_access_token).to.not.be.empty }) }) it("should get client when having a valid client_secret in body", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { client_name: "clientName", grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "GET", url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, headers: { Authorization: "Bearer " + response.body.registration_access_token, }, }).then((response) => { expect(response.body.client_name).to.equal("clientName") }) }) }) it("should fail for get client when Authorization header is not presented", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "GET", failOnStatusCode: false, url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, }).then((response) => { expect(response.status).to.eq(401) }) }) }) it("should update client name", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "PUT", failOnStatusCode: false, url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, headers: { Authorization: "Bearer " + response.body.registration_access_token, }, body: { client_id: "clientid", client_name: "clientName2", scope: "foo openid offline_access", grant_types: ["client_credentials"], }, }).then((response) => { expect(response.body.client_name).to.equal("clientName2") expect(response.body.client_id).to.not.equal("clientid") }) }) }) it("should not be able to choose the secret", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "PUT", failOnStatusCode: false, url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, headers: { Authorization: "Bearer " + response.body.registration_access_token, }, body: { client_id: "clientid", client_name: "clientName2", client_secret: "secret", scope: "foo openid offline_access", grant_types: ["client_credentials"], }, }).then((response) => { expect(response.status).to.eq(403) }) }) }) it("should fail to update client name when Authorization header is not presented", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { client_name: "clientName", grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "PUT", failOnStatusCode: false, url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, }).then((response) => { expect(response.status).to.eq(401) }) }) }) it("should fail to delete client when Authorization header is not presented", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { client_name: "clientName", grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "DELETE", failOnStatusCode: false, url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, }).then((response) => { expect(response.status).to.eq(401) }) }) }) it("should delete client when having an valid Authorization header", function () { cy.request({ method: "POST", url: Cypress.env("public_url") + "/oauth2/register", body: { client_name: "clientName", grant_types: ["client_credentials"], }, }).then((response) => { cy.request({ method: "DELETE", failOnStatusCode: false, url: Cypress.env("public_url") + "/oauth2/register/" + response.body.client_id, headers: { Authorization: "Bearer " + response.body.registration_access_token, }, }).then((response) => { expect(response.status).to.eq(204) }) }) }) })
JavaScript
hydra/cypress/integration/openid/logout.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { deleteClients, prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "openid", subject_type: "public", redirect_uris: [`${Cypress.env("client_url")}/openid/callback`], grant_types: ["authorization_code"], access_token_strategy: accessTokenStrategy, }) describe("OpenID Connect Logout", () => { before(() => { cy.clearCookies({ domain: null }) }) after(() => { deleteClients() }) describe("logout without id_token_hint", () => { beforeEach(() => { Cypress.Cookies.preserveOnce( "oauth2_authentication_session", "oauth2_authentication_session_insecure", "connect.sid", ) }) before(() => { deleteClients() }) const client = { ...nc(), backchannel_logout_uri: `${Cypress.env( "client_url", )}/openid/session/end/bc`, } it("should log in and remember login without id_token_hint", function () { cy.authCodeFlow( client, { login: { remember: true }, consent: { scope: ["openid"], remember: true, }, }, "openid", ) cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.true }) }) it("should show the logout page and complete logout without id_token_hint", () => { // cy.request(`${Cypress.env('client_url')}/openid/session/check`) // .its('body') // .then(({ has_session }) => { // expect(has_session).to.be.true; // }); cy.visit(`${Cypress.env("client_url")}/openid/session/end?simple=1`, { failOnStatusCode: false, }) cy.get("#accept").click() cy.get("h1").should( "contain", "Your log out request however succeeded.", ) }) it("should show the login screen again because we logged out", () => { cy.authCodeFlow( client, { login: { remember: false }, // login should have skip false because we removed the session.mak consent: { scope: ["openid"], remember: false, skip: true, }, createClient: false, }, "openid", ) }) }) // The Back-Channel test should run before the front-channel test because otherwise both tests need a long time to finish. describe.only("Back-Channel", () => { beforeEach(() => { Cypress.Cookies.preserveOnce( "oauth2_authentication_session", "oauth2_authentication_session_insecure", "connect.sid", ) }) before(() => { deleteClients() }) const client = { ...nc(), backchannel_logout_uri: `${Cypress.env( "client_url", )}/openid/session/end/bc`, } it("should log in and remember login with back-channel", function () { cy.authCodeFlow( client, { login: { remember: true }, consent: { scope: ["openid"], remember: true, }, }, "openid", ) cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.true }) }) it("should show the logout page and complete logout with back-channel", () => { cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.true }) cy.visit(`${Cypress.env("client_url")}/openid/session/end`, { failOnStatusCode: false, }) cy.get("#accept").click() cy.get("h1").should( "contain", "Your log out request however succeeded.", ) cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.false }) }) }) describe("Front-Channel", () => { beforeEach(() => { Cypress.Cookies.preserveOnce( "oauth2_authentication_session", "oauth2_authentication_session_insecure", "connect.sid", ) }) before(() => { deleteClients() }) const client = { ...nc(), frontchannel_logout_uri: `${Cypress.env( "client_url", )}/openid/session/end/fc`, } it("should log in and remember login with front-channel", () => { cy.authCodeFlow( client, { login: { remember: true }, consent: { scope: ["openid"], remember: true, }, }, "openid", ) cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.true }) }) it("should show the logout page and complete logout with front-channel", () => { cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.true }) cy.visit(`${Cypress.env("client_url")}/openid/session/end`, { failOnStatusCode: false, }) cy.get("#accept").click() cy.get("h1").should( "contain", "Your log out request however succeeded.", ) cy.request(`${Cypress.env("client_url")}/openid/session/check`) .its("body") .then(({ has_session }) => { expect(has_session).to.be.false }) }) }) }) }) })
JavaScript
hydra/cypress/integration/openid/prompt.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { createClient, prng } from "../../helpers" import qs from "querystring" const accessTokenStrategies = ["opaque", "jwt"] describe("OpenID Connect Prompt", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "openid", redirect_uris: [`${Cypress.env("client_url")}/openid/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should fail prompt=none when no session exists", function () { createClient(nc()).then((client) => { cy.visit( `${Cypress.env("client_url")}/openid/code?client_id=${ client.client_id }&client_secret=${client.client_secret}&prompt=none`, { failOnStatusCode: false }, ) cy.location().should(({ search, port }) => { const query = qs.parse(search.substr(1)) expect(query.error).to.equal("login_required") expect(port).to.equal(Cypress.env("client_port")) }) }) }) it("should pass with prompt=none if both login and consent were remembered", function () { createClient(nc()).then((client) => { cy.authCodeFlow( client, { login: { remember: true }, consent: { scope: ["openid"], remember: true, }, createClient: false, }, "openid", ) cy.request( `${Cypress.env("client_url")}/openid/code?client_id=${ client.client_id }&client_secret=${client.client_secret}&scope=openid`, ) .its("body") .then((body) => { const { result, token: { access_token }, } = body expect(result).to.equal("success") expect(access_token).to.not.be.empty }) }) }) it("should require login with prompt=login even when session exists", function () { createClient(nc()).then((client) => { cy.authCodeFlow( client, { login: { remember: true }, consent: { scope: ["openid"], remember: true, }, createClient: false, }, "openid", ) cy.request( `${Cypress.env("client_url")}/openid/code?client_id=${ client.client_id }&client_secret=${client.client_secret}&scope=openid&prompt=login`, ) .its("body") .then((body) => { expect(body).to.contain("Please log in") }) }) }) it("should require consent with prompt=consent even when session exists", function () { createClient(nc()).then((client) => { cy.authCodeFlow( client, { login: { remember: true }, consent: { scope: ["openid"], remember: true, }, createClient: false, }, "openid", ) cy.request( `${Cypress.env("client_url")}/openid/code?client_id=${ client.client_id }&client_secret=${ client.client_secret }&scope=openid&prompt=consent`, ) .its("body") .then((body) => { expect(body).to.contain( "An application requests access to your data!", ) }) }) }) }) }) })
JavaScript
hydra/cypress/integration/openid/revoke.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("OpenID Connect Token Revokation", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "openid offline_access", redirect_uris: [`${Cypress.env("client_url")}/openid/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should be able to revoke the access token", function () { const client = nc() cy.authCodeFlow( client, { consent: { scope: ["openid", "offline_access"] } }, "openid", ) cy.get("body") .invoke("text") .then((content) => { const { result } = JSON.parse(content) expect(result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/openid/revoke/at`) .its("body") .then((response) => { expect(response.result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/openid/userinfo`, { failOnStatusCode: false, }) .its("body") .then((response) => { expect(response.error).to.contain("request_unauthorized") }) }) it("should be able to revoke the refresh token", function () { const client = nc() cy.authCodeFlow( client, { consent: { scope: ["openid", "offline_access"] } }, "openid", ) cy.get("body") .invoke("text") .then((content) => { const { result } = JSON.parse(content) expect(result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/openid/revoke/rt`, { failOnStatusCode: false, }) .its("body") .then((response) => { expect(response.result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/openid/userinfo`, { failOnStatusCode: false, }) .its("body") .then((response) => { expect(response.error).to.contain("request_unauthorized") }) }) }) }) })
JavaScript
hydra/cypress/integration/openid/userinfo.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 import { prng } from "../../helpers" const accessTokenStrategies = ["opaque", "jwt"] describe("OpenID Connect Userinfo", () => { accessTokenStrategies.forEach((accessTokenStrategy) => { describe("access_token_strategy=" + accessTokenStrategy, function () { const nc = () => ({ client_secret: prng(), scope: "openid", redirect_uris: [`${Cypress.env("client_url")}/openid/callback`], grant_types: ["authorization_code", "refresh_token"], access_token_strategy: accessTokenStrategy, }) it("should return a proper userinfo response", function () { const client = nc() cy.authCodeFlow(client, { consent: { scope: ["openid"] } }, "openid") cy.get("body") .invoke("text") .then((content) => { const { result } = JSON.parse(content) expect(result).to.equal("success") }) cy.request(`${Cypress.env("client_url")}/openid/userinfo`) .its("body") .then(({ aud, sub } = {}) => { expect(sub).to.eq("[email protected]") expect(aud).to.not.be.empty }) }) }) }) })
JavaScript
hydra/cypress/plugins/index.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 // *********************************************************** // This example plugins/index.js can be used to load plugins // // You can change the location of this file or turn off loading // the plugins file with the 'pluginsFile' configuration option. // // You can read more here: // https://on.cypress.io/plugins-guide // *********************************************************** // This function is called when a project is opened or re-opened (e.g. due to // the project's config changing) module.exports = (on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config }
JavaScript
hydra/cypress/support/commands.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 // *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add("login", (email, password) => { ... }) // // // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This is will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) import { createClient, prng } from "../helpers" Cypress.Commands.add( "authCodeFlow", ( client, { override: { scope, client_id, client_secret } = {}, consent: { accept: acceptConsent = true, skip: skipConsent = false, remember: rememberConsent = false, scope: acceptScope = [], } = {}, login: { accept: acceptLogin = true, skip: skipLogin = false, remember: rememberLogin = false, username = "[email protected]", password = "foobar", } = {}, prompt = "", createClient: doCreateClient = true, } = {}, path = "oauth2", ) => { const run = (client) => { cy.visit( `${Cypress.env("client_url")}/${path}/code?client_id=${ client_id || client.client_id }&client_secret=${client_secret || client.client_secret}&scope=${( scope || client.scope ).replace(" ", "+")}&prompt=${prompt}`, { failOnStatusCode: false }, ) if (!skipLogin) { cy.get("#email").type(username, { delay: 1 }) cy.get("#password").type(password, { delay: 1 }) if (rememberLogin) { cy.get("#remember").click() } if (acceptLogin) { cy.get("#accept").click() } else { cy.get("#reject").click() } } if (!skipConsent) { acceptScope.forEach((s) => { cy.get(`#${s}`).click() }) if (rememberConsent) { cy.get("#remember").click() } if (acceptConsent) { cy.get("#accept").click() } else { cy.get("#reject").click() } } } if (doCreateClient) { createClient(client).should((client) => { run(client) }) return } run(client) }, ) Cypress.Commands.add( "authCodeFlowBrowser", ( client, { consent: { accept: acceptConsent = true, skip: skipConsent = false, remember: rememberConsent = false, scope: acceptScope = [], } = {}, login: { accept: acceptLogin = true, skip: skipLogin = false, remember: rememberLogin = false, username = "[email protected]", password = "foobar", } = {}, createClient: doCreateClient = true, } = {}, ) => { const run = (client) => { const codeChallenge = "QeNVR-BHuB6I2d0HycQzp2qUNNKi_-5QoR4fQSifLH0" const codeVerifier = "ZmRrenFxZ3pid3A0T0xqY29falJNUS5lWlY4SDBxS182U21uQkhjZ3UuOXpnd3NOak56d2lLMTVYemNNdHdNdlE5TW03WC1RZUlaM0N5R2FhdGRpNW1oVGhjbzVuRFBD" const state = prng() const authURL = new URL(`${Cypress.env("public_url")}/oauth2/auth`) authURL.searchParams.set("response_type", "code") authURL.searchParams.set("client_id", client.client_id) authURL.searchParams.set("redirect_uri", client.redirect_uris[0]) authURL.searchParams.set("scope", client.scope) authURL.searchParams.set("state", state) authURL.searchParams.set("code_challenge", codeChallenge) authURL.searchParams.set("code_challenge_method", "S256") cy.window().then((win) => { return win.open(authURL, "_self") }) if (!skipLogin) { cy.get("#email").type(username, { delay: 1 }) cy.get("#password").type(password, { delay: 1 }) if (rememberLogin) { cy.get("#remember").click() } if (acceptLogin) { cy.get("#accept").click() } else { cy.get("#reject").click() } } if (!skipConsent) { acceptScope.forEach((s) => { cy.get(`#${s}`).click() }) if (rememberConsent) { cy.get("#remember").click() } if (acceptConsent) { cy.get("#accept").click() } else { cy.get("#reject").click() } } return cy.location("search").then((search) => { const callbackParams = new URLSearchParams(search) const code = callbackParams.get("code") expect(code).to.not.be.empty return cy.request({ url: `${Cypress.env("public_url")}/oauth2/token`, method: "POST", form: true, body: { grant_type: "authorization_code", client_id: client.client_id, redirect_uri: client.redirect_uris[0], code: code, code_verifier: codeVerifier, }, }) }) } if (doCreateClient) { createClient(client).then(run) return } run(client) }, ) Cypress.Commands.add("refreshTokenBrowser", (client, token) => cy.request({ url: `${Cypress.env("public_url")}/oauth2/token`, method: "POST", form: true, body: { grant_type: "refresh_token", client_id: client.client_id, refresh_token: token, }, failOnStatusCode: false, }), )
JavaScript
hydra/cypress/support/index.js
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 // *********************************************************** // This example support/index.js is processed and // loaded automatically before your test files. // // This is a great place to put global configuration and // behavior that modifies Cypress. // // You can change the location of this file or turn off // automatically serving support files with the // 'supportFile' configuration option. // // You can read more here: // https://on.cypress.io/configuration // *********************************************************** // Import commands.js using ES2015 syntax: import "./commands" // Alternatively you can use CommonJS syntax: // require('./commands')
Markdown
hydra/docs/flow-cache-design-doc.md
# Flow Cache Design Doc ## Overview This design doc outlines the proposed solution for caching the flow object in the OAuth2 exchange between the Client, Ory Hydra, and the Consent and Login UIs. The flow object contains the state of the authorization request. ## Problem Statement Currently, the flow object is stored in the database on the Ory Hydra server. This approach has several drawbacks: - Each step of the OAuth2 flow (initialization, consent, login, etc.) requires a database query to retrieve the flow object, and another to update it. - Each part of the exchanges supplies different values (login challenge, consent challenge, etc.) to identify the flow object. This means the database table has multiple indices that slow down insertions. ## Proposed Solution The proposed solution is to store the flow object in client cookies and URLs. This way, the flow object is written only once when the flow is completed and the final authorization code is generated. ### Requirements - The flow object must be stored in client cookies and URLs. - The flow object must be secure and protect against unauthorized access. - The flow object must be persistent, so that the flow can be resumed if the user navigates away from the page or closes the browser. - The flow object must be scalable and able to handle a large number of concurrent requests. ### Architecture The proposed architecture for the flow cache is as follows: - Store the flow object in an AEAD encrypted cookie. - Pass a partial flow around in the URL. - Use a secure connection to protect against unauthorized access. ```mermaid sequenceDiagram actor Client participant Hydra participant LoginUI as Login UI participant ConsentUI as Consent UI % participant Callback autonumber Client->>+Hydra: GET /oauth2/auth?client_id=CLIENT_ID&response_type=code&scope=SCOPES&state=STATE Hydra->>-Client: Redirect to <br> http://login.local/?login_challenge=LOGIN_CHALLENGE Client->>+LoginUI: GET /?login_challenge=LOGIN_CHALLENGE LoginUI->>Hydra: GET /admin/oauth2/auth/requests/login Hydra->>LoginUI: oAuth2LoginRequest alt accept login LoginUI->>Hydra: PUT /admin/oauth2/auth/requests/login/accept else reject login LoginUI->>Hydra: PUT /admin/oauth2/auth/requests/login/reject end Hydra->>LoginUI: oAuth2RedirectTo LoginUI->>-Client: Redirect to <br> http://hydra.local/oauth2/auth?client_id=CLIENT_ID&login_verifier=LOGIN_VERIFIER&response_type=code&scope=SCOPES&state=STATE Client->>+Hydra: GET /oauth2/auth?client_id=CLIENT_ID&login_verifier=LOGIN_VERIFIER&response_type=code&scope=SCOPES&state=STATE Hydra->>-Client: Redirect to <br> http://consent.local/?consent_challenge=CONSENT_CHALLENGE Client->>+ConsentUI: GET /?consent_challenge=CONSENT_CHALLENGE ConsentUI->>Hydra: GET /admin/oauth2/auth/requests/consent Hydra->>ConsentUI: oAuth2ConsentRequest alt accept login ConsentUI->>Hydra: PUT /admin/oauth2/auth/requests/consent/accept else reject login ConsentUI->>Hydra: PUT /admin/oauth2/auth/requests/consent/reject end Hydra->>ConsentUI: oAuth2RedirectTo ConsentUI->>-Client: Redirect to <br> http://hydra.local/oauth2/auth?client_id=CLIENT_ID&consent_verifier=CONSENT_VERIFIER&response_type=code&scope=SCOPES&state=STATE Client->>+Hydra: GET /oauth2/auth?client_id=CLIENT_ID&consent_verifier=CONSENT_VERIFIER&response_type=code&scope=SCOPES&state=STATE Hydra->>-Client: Redirect to <br> http://callback.local/callback?code=AUTH_CODE&scope=SCOPES&state=STATE Note over Hydra,Client: next, exchange code for token. % Client->>+Callback: GET /callback?code=AUTH_CODE&scope=SCOPES&state=STATE % Callback->>-Client: Return Authorization Code ``` Step 2: - Set the whole flow as an AEAD encrypted cookie on the client - The cookie is keyed by the `state`, so that multiple flows can run in parallel from one cookie jar - Set the `LOGIN_CHALLENGE` to the AEAD-encrypted flow Step 5: - Decrypt the flow from the `LOGIN_CHALLENGE`, return the `oAuth2LoginRequest` Step 8: - Encode the flow into the redirect URL in `oAuth2RedirectTo` as the `LOGIN_VERIFIER` Step 11 - Check that the login challenge in the `LOGIN_VERIFIER` matches the challenge in the flow cookie. - Update the flow based on the request from the `LOGIN_VERIFIER` - Update the cookie - Set the `CONSENT_CHALLENGE` to the AEAD-encrypted flow Step 14: - Decrypt the flow from the `CONSENT_CHALLENGE` Step 17: - Encode the flow into the redirect URL in `oAuth2RedirectTo` as the `CONSENT_VERIFIER` Step 20 - Check that the consent challenge in the `CONSENT_VERIFIER` matches the challenge in the flow cookie. - Update the flow based on the request from the `CONSENT_VERIFIER` - Update the cookie - Write the flow to the database - Continue the flow as currently implemented (generate the authentication code, return the code, etc.) ### Client HTTP requests For reference, these HTTP requests are issued by the client: ``` GET http://hydra.local/oauth2/auth?client_id=CLIENT_ID&nonce=NONCE&response_type=code&scope=SCOPES&state=STATE Redirect to http://login.local/?login_challenge=LOGIN_CHALLENGE GET http://login.local/?login_challenge=LOGIN_CHALLENGE Redirect to http://hydra.local/oauth2/auth?client_id=CLIENT_ID&login_verifier=LOGIN_VERIFIER&nonce=NONCE&response_type=code&scope=SCOPES&state=STATE GET http://hydra.local/oauth2/auth?client_id=CLIENT_ID&login_verifier=LOGIN_VERIFIER&nonce=NONCE&response_type=code&scope=SCOPES&state=STATE Redirect to http://consent.local/?consent_challenge=CONSENT_CHALLENGE GET http://consent.local/?consent_challenge=CONSENT_CHALLENGE Redirect to http://hydra.local/oauth2/auth?client_id=CLIENT_ID&consent_verifier=CONSENT_VERIFIER&nonce=NONCE&response_type=code&scope=SCOPES&state=STATE GET http://hydra.local/oauth2/auth?client_id=CLIENT_ID&consent_verifier=CONSENT_VERIFIER&nonce=NONCE&response_type=code&scope=SCOPES&state=STATE Redirect to http://callback.local/callback?code=AUTH_CODE&scope=SCOPES&state=STATE GET http://callback.local/callback?code=AUTH_CODE&scope=SCOPES&state=STATE ``` ### Implementation The implementation of the flow cache will involve the following steps: 1. Modify the Ory Hydra server to store the flow object in an AEAD encrypted cookie. 2. Modify the Consent and Login UIs to include the flow object in the URL. 3. Use HTTPS to protect against unauthorized access. ## Conclusion The proposed solution for caching the flow object in the OAuth2 exchange between the Client, Ory Hydra, and the Consent and Login UIs is to store the flow object in client cookies and URLs. This approach eliminates the need for a distributed cache and provides a scalable and secure solution. The flow object will be stored in an AEAD encrypted cookie and passed around in the URL. HTTPS will be used to protect against unauthorized access.
Markdown
hydra/docs/README.md
# Documentation Please find the documentation at [www.ory.sh/docs/hydra](https://www.ory.sh/docs/hydra). To contribute to the documentation, please head over to: [github.com/ory/docs/tree/master/docs/hydra](https://github.com/ory/docs/tree/master/docs/hydra)
Go
hydra/driver/factory.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package driver import ( "context" "io/fs" "github.com/ory/hydra/v2/driver/config" "github.com/ory/x/configx" "github.com/ory/x/logrusx" "github.com/ory/x/otelx" "github.com/ory/x/popx" "github.com/ory/x/servicelocatorx" ) type ( options struct { preload bool validate bool opts []configx.OptionModifier config *config.DefaultProvider // The first default refers to determining the NID at startup; the second default referes to the fact that the Contextualizer may dynamically change the NID. skipNetworkInit bool tracerWrapper TracerWrapper extraMigrations []fs.FS goMigrations []popx.Migration } OptionsModifier func(*options) TracerWrapper func(*otelx.Tracer) *otelx.Tracer ) func newOptions() *options { return &options{ validate: true, preload: true, opts: []configx.OptionModifier{}, } } func WithConfig(config *config.DefaultProvider) OptionsModifier { return func(o *options) { o.config = config } } func WithOptions(opts ...configx.OptionModifier) OptionsModifier { return func(o *options) { o.opts = append(o.opts, opts...) } } // DisableValidation validating the config. // // This does not affect schema validation! func DisableValidation() OptionsModifier { return func(o *options) { o.validate = false } } // DisablePreloading will not preload the config. func DisablePreloading() OptionsModifier { return func(o *options) { o.preload = false } } func SkipNetworkInit() OptionsModifier { return func(o *options) { o.skipNetworkInit = true } } // WithTracerWrapper sets a function that wraps the tracer. func WithTracerWrapper(wrapper TracerWrapper) OptionsModifier { return func(o *options) { o.tracerWrapper = wrapper } } // WithExtraMigrations specifies additional database migration. func WithExtraMigrations(m ...fs.FS) OptionsModifier { return func(o *options) { o.extraMigrations = append(o.extraMigrations, m...) } } func WithGoMigrations(m ...popx.Migration) OptionsModifier { return func(o *options) { o.goMigrations = append(o.goMigrations, m...) } } func New(ctx context.Context, sl *servicelocatorx.Options, opts []OptionsModifier) (Registry, error) { o := newOptions() for _, f := range opts { f(o) } l := sl.Logger() if l == nil { l = logrusx.New("Ory Hydra", config.Version) } ctxter := sl.Contextualizer() c := o.config if c == nil { var err error c, err = config.New(ctx, l, o.opts...) if err != nil { l.WithError(err).Error("Unable to instantiate configuration.") return nil, err } } if o.validate { if err := config.Validate(ctx, l, c); err != nil { return nil, err } } r, err := NewRegistryWithoutInit(c, l) if err != nil { l.WithError(err).Error("Unable to create service registry.") return nil, err } if o.tracerWrapper != nil { r.WithTracerWrapper(o.tracerWrapper) } if err = r.Init(ctx, o.skipNetworkInit, false, ctxter, o.extraMigrations, o.goMigrations); err != nil { l.WithError(err).Error("Unable to initialize service registry.") return nil, err } // Avoid cold cache issues on boot: if o.preload { CallRegistry(ctx, r) } c.Source(ctx).SetTracer(ctx, r.Tracer(ctx)) return r, nil }
Go
hydra/driver/registry.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package driver import ( "context" "io/fs" "net/http" "go.opentelemetry.io/otel/trace" "github.com/ory/hydra/v2/internal/kratos" "github.com/ory/x/httprouterx" "github.com/ory/x/popx" "github.com/ory/hydra/v2/aead" "github.com/ory/hydra/v2/hsm" "github.com/ory/x/contextx" "github.com/ory/hydra/v2/oauth2/trust" "github.com/pkg/errors" "github.com/ory/x/errorsx" "github.com/ory/fosite" foauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/x/logrusx" "github.com/ory/hydra/v2/persistence" prometheus "github.com/ory/x/prometheusx" "github.com/ory/x/dbal" "github.com/ory/x/healthx" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/jwk" "github.com/ory/hydra/v2/oauth2" "github.com/ory/hydra/v2/x" ) type Registry interface { dbal.Driver Init(ctx context.Context, skipNetworkInit bool, migrate bool, ctxer contextx.Contextualizer, extraMigrations []fs.FS, goMigrations []popx.Migration) error WithBuildInfo(v, h, d string) Registry WithConfig(c *config.DefaultProvider) Registry WithContextualizer(ctxer contextx.Contextualizer) Registry WithLogger(l *logrusx.Logger) Registry WithTracer(t trace.Tracer) Registry WithTracerWrapper(TracerWrapper) Registry WithKratos(k kratos.Client) Registry x.HTTPClientProvider GetJWKSFetcherStrategy() fosite.JWKSFetcherStrategy contextx.Provider config.Provider persistence.Provider x.RegistryLogger x.RegistryWriter x.RegistryCookieStore client.Registry consent.Registry jwk.Registry trust.Registry oauth2.Registry PrometheusManager() *prometheus.MetricsManager x.TracingProvider FlowCipher() *aead.XChaCha20Poly1305 kratos.Provider RegisterRoutes(ctx context.Context, admin *httprouterx.RouterAdmin, public *httprouterx.RouterPublic) ClientHandler() *client.Handler KeyHandler() *jwk.Handler ConsentHandler() *consent.Handler OAuth2Handler() *oauth2.Handler HealthHandler() *healthx.Handler OAuth2AwareMiddleware() func(h http.Handler) http.Handler OAuth2HMACStrategy() *foauth2.HMACSHAStrategy WithOAuth2Provider(f fosite.OAuth2Provider) WithConsentStrategy(c consent.Strategy) WithHsmContext(h hsm.Context) } func NewRegistryFromDSN(ctx context.Context, c *config.DefaultProvider, l *logrusx.Logger, skipNetworkInit bool, migrate bool, ctxer contextx.Contextualizer) (Registry, error) { registry, err := NewRegistryWithoutInit(c, l) if err != nil { return nil, err } if err := registry.Init(ctx, skipNetworkInit, migrate, ctxer, nil, nil); err != nil { return nil, err } return registry, nil } func NewRegistryWithoutInit(c *config.DefaultProvider, l *logrusx.Logger) (Registry, error) { driver, err := dbal.GetDriverFor(c.DSN()) if err != nil { return nil, errorsx.WithStack(err) } registry, ok := driver.(Registry) if !ok { return nil, errors.Errorf("driver of type %T does not implement interface Registry", driver) } registry = registry.WithLogger(l).WithConfig(c).WithBuildInfo(config.Version, config.Commit, config.Date) return registry, nil } func CallRegistry(ctx context.Context, r Registry) { r.ClientValidator() r.ClientManager() r.ClientHasher() r.ConsentManager() r.ConsentStrategy() r.SubjectIdentifierAlgorithm(ctx) r.KeyManager() r.KeyCipher() r.FlowCipher() r.OAuth2Storage() r.OAuth2Provider() r.AudienceStrategy() r.AccessTokenJWTStrategy() r.OpenIDJWTStrategy() r.OpenIDConnectRequestValidator() r.PrometheusManager() r.Tracer(ctx) }
Go
hydra/driver/registry_base.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package driver import ( "context" "crypto/sha256" "fmt" "net/http" "time" "github.com/gorilla/sessions" "github.com/hashicorp/go-retryablehttp" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/rs/cors" "go.opentelemetry.io/otel/trace" "github.com/ory/fosite" "github.com/ory/fosite/compose" foauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/handler/openid" "github.com/ory/herodot" "github.com/ory/hydra/v2/aead" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/fositex" "github.com/ory/hydra/v2/hsm" "github.com/ory/hydra/v2/internal/kratos" "github.com/ory/hydra/v2/jwk" "github.com/ory/hydra/v2/oauth2" "github.com/ory/hydra/v2/oauth2/trust" "github.com/ory/hydra/v2/persistence" "github.com/ory/hydra/v2/x" "github.com/ory/hydra/v2/x/oauth2cors" "github.com/ory/x/contextx" "github.com/ory/x/healthx" "github.com/ory/x/httprouterx" "github.com/ory/x/httpx" "github.com/ory/x/logrusx" "github.com/ory/x/otelx" "github.com/ory/x/popx" prometheus "github.com/ory/x/prometheusx" ) var ( _ contextx.Provider = (*RegistryBase)(nil) ) type RegistryBase struct { l *logrusx.Logger al *logrusx.Logger conf *config.DefaultProvider ch *client.Handler fh fosite.Hasher jwtGrantH *trust.Handler jwtGrantV *trust.GrantValidator kh *jwk.Handler cv *client.Validator ctxer contextx.Contextualizer hh *healthx.Handler migrationStatus *popx.MigrationStatuses kc *aead.AESGCM flowc *aead.XChaCha20Poly1305 cos consent.Strategy writer herodot.Writer hsm hsm.Context forv *openid.OpenIDConnectRequestValidator fop fosite.OAuth2Provider coh *consent.Handler oah *oauth2.Handler sia map[string]consent.SubjectIdentifierAlgorithm trc *otelx.Tracer tracerWrapper func(*otelx.Tracer) *otelx.Tracer pmm *prometheus.MetricsManager oa2mw func(h http.Handler) http.Handler arhs []oauth2.AccessRequestHook buildVersion string buildHash string buildDate string r Registry persister persistence.Persister jfs fosite.JWKSFetcherStrategy oc fosite.Configurator oidcs jwk.JWTSigner ats jwk.JWTSigner hmacs *foauth2.HMACSHAStrategy fc *fositex.Config publicCORS *cors.Cors kratos kratos.Client } func (m *RegistryBase) GetJWKSFetcherStrategy() fosite.JWKSFetcherStrategy { if m.jfs == nil { m.jfs = fosite.NewDefaultJWKSFetcherStrategy(fosite.JWKSFetcherWithHTTPClientSource(func(ctx context.Context) *retryablehttp.Client { return m.HTTPClient(ctx) })) } return m.jfs } func (m *RegistryBase) WithContextualizer(ctxer contextx.Contextualizer) Registry { m.ctxer = ctxer return m.r } func (m *RegistryBase) Contextualizer() contextx.Contextualizer { if m.ctxer == nil { panic("registry Contextualizer not set") } return m.ctxer } func (m *RegistryBase) with(r Registry) *RegistryBase { m.r = r return m } func (m *RegistryBase) WithBuildInfo(version, hash, date string) Registry { m.buildVersion = version m.buildHash = hash m.buildDate = date return m.r } func (m *RegistryBase) OAuth2AwareMiddleware() func(h http.Handler) http.Handler { if m.oa2mw == nil { m.oa2mw = oauth2cors.Middleware(m.r) } return m.oa2mw } func (m *RegistryBase) addPublicCORSOnHandler(ctx context.Context) func(http.Handler) http.Handler { corsConfig, corsEnabled := m.Config().CORS(ctx, config.PublicInterface) if !corsEnabled { return func(h http.Handler) http.Handler { return h } } if m.publicCORS == nil { m.publicCORS = cors.New(corsConfig) } return func(h http.Handler) http.Handler { return m.publicCORS.Handler(h) } } func (m *RegistryBase) RegisterRoutes(ctx context.Context, admin *httprouterx.RouterAdmin, public *httprouterx.RouterPublic) { m.HealthHandler().SetHealthRoutes(admin.Router, true) m.HealthHandler().SetVersionRoutes(admin.Router) m.HealthHandler().SetHealthRoutes(public.Router, false, healthx.WithMiddleware(m.addPublicCORSOnHandler(ctx))) admin.Handler("GET", prometheus.MetricsPrometheusPath, promhttp.Handler()) m.ConsentHandler().SetRoutes(admin) m.KeyHandler().SetRoutes(admin, public, m.OAuth2AwareMiddleware()) m.ClientHandler().SetRoutes(admin, public) m.OAuth2Handler().SetRoutes(admin, public, m.OAuth2AwareMiddleware()) m.JWTGrantHandler().SetRoutes(admin) } func (m *RegistryBase) BuildVersion() string { return m.buildVersion } func (m *RegistryBase) BuildDate() string { return m.buildDate } func (m *RegistryBase) BuildHash() string { return m.buildHash } func (m *RegistryBase) WithConfig(c *config.DefaultProvider) Registry { m.conf = c return m.r } func (m *RegistryBase) Writer() herodot.Writer { if m.writer == nil { h := herodot.NewJSONWriter(m.Logger()) h.ErrorEnhancer = x.ErrorEnhancer m.writer = h } return m.writer } func (m *RegistryBase) WithLogger(l *logrusx.Logger) Registry { m.l = l return m.r } func (m *RegistryBase) WithTracer(t trace.Tracer) Registry { m.trc = new(otelx.Tracer).WithOTLP(t) return m.r } func (m *RegistryBase) WithTracerWrapper(wrapper TracerWrapper) Registry { m.tracerWrapper = wrapper return m.r } func (m *RegistryBase) WithKratos(k kratos.Client) Registry { m.kratos = k return m.r } func (m *RegistryBase) Logger() *logrusx.Logger { if m.l == nil { m.l = logrusx.New("Ory Hydra", m.BuildVersion()) } return m.l } func (m *RegistryBase) AuditLogger() *logrusx.Logger { if m.al == nil { m.al = logrusx.NewAudit("Ory Hydra", m.BuildVersion()) m.al.UseConfig(m.Config().Source(contextx.RootContext)) } return m.al } func (m *RegistryBase) ClientHasher() fosite.Hasher { if m.fh == nil { m.fh = x.NewHasher(m.Config()) } return m.fh } func (m *RegistryBase) ClientHandler() *client.Handler { if m.ch == nil { m.ch = client.NewHandler(m.r) } return m.ch } func (m *RegistryBase) ClientValidator() *client.Validator { if m.cv == nil { m.cv = client.NewValidator(m.r) } return m.cv } func (m *RegistryBase) KeyHandler() *jwk.Handler { if m.kh == nil { m.kh = jwk.NewHandler(m.r) } return m.kh } func (m *RegistryBase) JWTGrantHandler() *trust.Handler { if m.jwtGrantH == nil { m.jwtGrantH = trust.NewHandler(m.r) } return m.jwtGrantH } func (m *RegistryBase) GrantValidator() *trust.GrantValidator { if m.jwtGrantV == nil { m.jwtGrantV = trust.NewGrantValidator() } return m.jwtGrantV } func (m *RegistryBase) HealthHandler() *healthx.Handler { if m.hh == nil { m.hh = healthx.NewHandler(m.Writer(), m.buildVersion, healthx.ReadyCheckers{ "database": func(_ *http.Request) error { return m.r.Ping() }, "migrations": func(r *http.Request) error { if m.migrationStatus != nil && !m.migrationStatus.HasPending() { return nil } status, err := m.r.Persister().MigrationStatus(r.Context()) if err != nil { return err } if status.HasPending() { err := errors.Errorf("migrations have not yet been fully applied: %+v", status) m.Logger().WithField("status", fmt.Sprintf("%+v", status)).WithError(err).Warn("Instance is not yet ready because migrations have not yet been fully applied.") return err } m.migrationStatus = &status return nil }, }) } return m.hh } func (m *RegistryBase) ConsentStrategy() consent.Strategy { if m.cos == nil { m.cos = consent.NewStrategy(m.r, m.Config()) } return m.cos } func (m *RegistryBase) KeyCipher() *aead.AESGCM { if m.kc == nil { m.kc = aead.NewAESGCM(m.Config()) } return m.kc } func (m *RegistryBase) FlowCipher() *aead.XChaCha20Poly1305 { if m.flowc == nil { m.flowc = aead.NewXChaCha20Poly1305(m.Config()) } return m.flowc } func (m *RegistryBase) CookieStore(ctx context.Context) (sessions.Store, error) { var keys [][]byte secrets, err := m.conf.GetCookieSecrets(ctx) if err != nil { return nil, err } for _, k := range secrets { encrypt := sha256.Sum256(k) keys = append(keys, k, encrypt[:]) } cs := sessions.NewCookieStore(keys...) cs.Options.Secure = m.Config().CookieSecure(ctx) cs.Options.HttpOnly = true // CookieStore MaxAge is set to 86400 * 30 by default. This prevents secure cookies retrieval with expiration > 30 days. // MaxAge(0) disables internal MaxAge check by SecureCookie, see: // // https://github.com/ory/hydra/pull/2488#discussion_r618992698 cs.MaxAge(0) if domain := m.Config().CookieDomain(ctx); domain != "" { cs.Options.Domain = domain } cs.Options.Path = "/" if sameSite := m.Config().CookieSameSiteMode(ctx); sameSite != 0 { cs.Options.SameSite = sameSite } return cs, nil } func (m *RegistryBase) HTTPClient(ctx context.Context, opts ...httpx.ResilientOptions) *retryablehttp.Client { opts = append(opts, httpx.ResilientClientWithLogger(m.Logger()), httpx.ResilientClientWithMaxRetry(2), httpx.ResilientClientWithConnectionTimeout(30*time.Second)) tracer := m.Tracer(ctx) if tracer.IsLoaded() { opts = append(opts, httpx.ResilientClientWithTracer(tracer.Tracer())) } if m.Config().ClientHTTPNoPrivateIPRanges() { opts = append( opts, httpx.ResilientClientDisallowInternalIPs(), httpx.ResilientClientAllowInternalIPRequestsTo(m.Config().ClientHTTPPrivateIPExceptionURLs()...), ) } return httpx.NewResilientClient(opts...) } func (m *RegistryBase) OAuth2Provider() fosite.OAuth2Provider { if m.fop != nil { return m.fop } m.fop = fosite.NewOAuth2Provider(m.r.OAuth2Storage(), m.OAuth2ProviderConfig()) return m.fop } func (m *RegistryBase) OpenIDJWTStrategy() jwk.JWTSigner { if m.oidcs != nil { return m.oidcs } m.oidcs = jwk.NewDefaultJWTSigner(m.Config(), m.r, x.OpenIDConnectKeyName) return m.oidcs } func (m *RegistryBase) AccessTokenJWTStrategy() jwk.JWTSigner { if m.ats != nil { return m.ats } m.ats = jwk.NewDefaultJWTSigner(m.Config(), m.r, x.OAuth2JWTKeyName) return m.ats } func (m *RegistryBase) OAuth2HMACStrategy() *foauth2.HMACSHAStrategy { if m.hmacs != nil { return m.hmacs } m.hmacs = compose.NewOAuth2HMACStrategy(m.OAuth2Config()) return m.hmacs } func (m *RegistryBase) OAuth2Config() *fositex.Config { if m.fc != nil { return m.fc } m.fc = fositex.NewConfig(m.r) return m.fc } func (m *RegistryBase) OAuth2ProviderConfig() fosite.Configurator { if m.oc != nil { return m.oc } conf := m.OAuth2Config() hmacAtStrategy := m.OAuth2HMACStrategy() oidcSigner := m.OpenIDJWTStrategy() atSigner := m.AccessTokenJWTStrategy() jwtAtStrategy := &foauth2.DefaultJWTStrategy{ Signer: atSigner, HMACSHAStrategy: hmacAtStrategy, Config: conf, } conf.LoadDefaultHandlers(&compose.CommonStrategy{ CoreStrategy: fositex.NewTokenStrategy(m.Config(), hmacAtStrategy, &foauth2.DefaultJWTStrategy{ Signer: jwtAtStrategy, HMACSHAStrategy: hmacAtStrategy, Config: conf, }), OpenIDConnectTokenStrategy: &openid.DefaultStrategy{ Config: conf, Signer: oidcSigner, }, Signer: oidcSigner, }) m.oc = conf return m.oc } func (m *RegistryBase) OpenIDConnectRequestValidator() *openid.OpenIDConnectRequestValidator { if m.forv == nil { m.forv = openid.NewOpenIDConnectRequestValidator(&openid.DefaultStrategy{ Config: m.OAuth2ProviderConfig(), Signer: m.OpenIDJWTStrategy(), }, m.OAuth2ProviderConfig()) } return m.forv } func (m *RegistryBase) AudienceStrategy() fosite.AudienceMatchingStrategy { return fosite.DefaultAudienceMatchingStrategy } func (m *RegistryBase) ConsentHandler() *consent.Handler { if m.coh == nil { m.coh = consent.NewHandler(m.r, m.Config()) } return m.coh } func (m *RegistryBase) OAuth2Handler() *oauth2.Handler { if m.oah == nil { m.oah = oauth2.NewHandler(m.r, m.Config()) } return m.oah } func (m *RegistryBase) SubjectIdentifierAlgorithm(ctx context.Context) map[string]consent.SubjectIdentifierAlgorithm { if m.sia == nil { m.sia = map[string]consent.SubjectIdentifierAlgorithm{} for _, t := range m.Config().SubjectTypesSupported(ctx) { switch t { case "public": m.sia["public"] = consent.NewSubjectIdentifierAlgorithmPublic() case "pairwise": m.sia["pairwise"] = consent.NewSubjectIdentifierAlgorithmPairwise([]byte(m.Config().SubjectIdentifierAlgorithmSalt(ctx))) } } } return m.sia } func (m *RegistryBase) Tracer(_ context.Context) *otelx.Tracer { if m.trc == nil { t, err := otelx.New("Ory Hydra", m.l, m.conf.Tracing()) if err != nil { m.Logger().WithError(err).Error("Unable to initialize Tracer.") } else { // Wrap the tracer if required if m.tracerWrapper != nil { t = m.tracerWrapper(t) } m.trc = t } } if m.trc.Tracer() == nil { m.trc = otelx.NewNoop(m.l, m.Config().Tracing()) } return m.trc } func (m *RegistryBase) PrometheusManager() *prometheus.MetricsManager { if m.pmm == nil { m.pmm = prometheus.NewMetricsManagerWithPrefix("hydra", prometheus.HTTPMetrics, m.buildVersion, m.buildHash, m.buildDate) } return m.pmm } func (m *RegistryBase) Persister() persistence.Persister { return m.persister } // Config returns the configuration for the given context. It may or may not be the same as the global configuration. func (m *RegistryBase) Config() *config.DefaultProvider { return m.conf } // WithOAuth2Provider forces an oauth2 provider which is only used for testing. func (m *RegistryBase) WithOAuth2Provider(f fosite.OAuth2Provider) { m.fop = f } // WithConsentStrategy forces a consent strategy which is only used for testing. func (m *RegistryBase) WithConsentStrategy(c consent.Strategy) { m.cos = c } func (m *RegistryBase) AccessRequestHooks() []oauth2.AccessRequestHook { if m.arhs == nil { m.arhs = []oauth2.AccessRequestHook{ oauth2.RefreshTokenHook(m), oauth2.TokenHook(m), } } return m.arhs } func (m *RegistryBase) WithHsmContext(h hsm.Context) { m.hsm = h } func (m *RegistryBase) HSMContext() hsm.Context { if m.hsm == nil { m.hsm = hsm.NewContext(m.Config(), m.l) } return m.hsm } func (m *RegistrySQL) ClientAuthenticator() x.ClientAuthenticator { return m.OAuth2Provider().(*fosite.Fosite) } func (m *RegistryBase) Kratos() kratos.Client { if m.kratos == nil { m.kratos = kratos.New(m) } return m.kratos }
Go
hydra/driver/registry_base_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package driver import ( "context" "errors" "fmt" "io" "net/http" "net/http/httptest" "testing" "github.com/ory/x/randx" "github.com/stretchr/testify/require" "github.com/ory/x/httpx" "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" "github.com/ory/hydra/v2/driver/config" "github.com/ory/x/configx" "github.com/ory/x/contextx" "github.com/ory/x/logrusx" "github.com/gorilla/sessions" ) func TestGetJWKSFetcherStrategyHostEnforcment(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") c := config.MustNew(context.Background(), l, configx.WithConfigFiles("../internal/.hydra.yaml")) c.MustSet(ctx, config.KeyDSN, "memory") c.MustSet(ctx, config.HSMEnabled, "false") c.MustSet(ctx, config.KeyClientHTTPNoPrivateIPRanges, true) registry, err := NewRegistryWithoutInit(c, l) require.NoError(t, err) _, err = registry.GetJWKSFetcherStrategy().Resolve(ctx, "http://localhost:8080", true) require.ErrorAs(t, err, new(httpx.ErrPrivateIPAddressDisallowed)) } func TestRegistryBase_newKeyStrategy_handlesNetworkError(t *testing.T) { // Test ensures any network specific error is logged with a // specific message when attempting to create a new key strategy: issue #2338 hook := test.Hook{} // Test hook for asserting log messages ctx := context.Background() l := logrusx.New("", "", logrusx.WithHook(&hook)) l.Logrus().SetOutput(io.Discard) l.Logrus().ExitFunc = func(int) {} // Override the exit func to avoid call to os.Exit // Create a config and set a valid but unresolvable DSN c := config.MustNew(context.Background(), l, configx.WithConfigFiles("../internal/.hydra.yaml")) c.MustSet(ctx, config.KeyDSN, "postgres://user:[email protected]:9999/postgres") c.MustSet(ctx, config.HSMEnabled, "false") registry, err := NewRegistryWithoutInit(c, l) if err != nil { t.Errorf("Failed to create registry: %s", err) return } r := registry.(*RegistrySQL) r.initialPing = failedPing(errors.New("snizzles")) _ = r.Init(context.Background(), true, false, &contextx.TestContextualizer{}, nil, nil) registryBase := RegistryBase{r: r, l: l} registryBase.WithConfig(c) assert.Equal(t, logrus.FatalLevel, hook.LastEntry().Level) assert.Contains(t, hook.LastEntry().Message, "snizzles") } func TestRegistryBase_CookieStore_MaxAgeZero(t *testing.T) { // Test ensures that CookieStore MaxAge option is equal to zero after initialization ctx := context.Background() r := new(RegistryBase) r.WithConfig(config.MustNew(context.Background(), logrusx.New("", ""), configx.WithValue(config.KeyGetSystemSecret, []string{randx.MustString(32, randx.AlphaNum)}))) s, err := r.CookieStore(ctx) require.NoError(t, err) cs := s.(*sessions.CookieStore) assert.Equal(t, cs.Options.MaxAge, 0) } func TestRegistryBase_HTTPClient(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusOK) })) defer ts.Close() t.Setenv("CLIENTS_HTTP_PRIVATE_IP_EXCEPTION_URLS", fmt.Sprintf("[%q]", ts.URL+"/exception/*")) ctx := context.Background() r := new(RegistryBase) r.WithConfig(config.MustNew( ctx, logrusx.New("", ""), configx.WithValues(map[string]interface{}{ config.KeyClientHTTPNoPrivateIPRanges: true, }), )) t.Run("case=matches exception glob", func(t *testing.T) { res, err := r.HTTPClient(ctx).Get(ts.URL + "/exception/foo") require.NoError(t, err) assert.Equal(t, 200, res.StatusCode) }) t.Run("case=does not match exception glob", func(t *testing.T) { _, err := r.HTTPClient(ctx).Get(ts.URL + "/foo") require.Error(t, err) }) }
Go
hydra/driver/registry_nosqlite.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 //go:build !sqlite // +build !sqlite package driver func (m *RegistrySQL) CanHandle(dsn string) bool { return m.alwaysCanHandle(dsn) }
Go
hydra/driver/registry_sql.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package driver import ( "context" "io/fs" "strings" "time" "github.com/gobuffalo/pop/v6" _ "github.com/jackc/pgx/v4/stdlib" "github.com/luna-duclos/instrumentedsql" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/consent" "github.com/ory/hydra/v2/hsm" "github.com/ory/hydra/v2/jwk" "github.com/ory/hydra/v2/oauth2/trust" "github.com/ory/hydra/v2/persistence/sql" "github.com/ory/hydra/v2/x" "github.com/ory/x/contextx" "github.com/ory/x/dbal" "github.com/ory/x/errorsx" otelsql "github.com/ory/x/otelx/sql" "github.com/ory/x/popx" "github.com/ory/x/resilience" "github.com/ory/x/sqlcon" ) type RegistrySQL struct { *RegistryBase defaultKeyManager jwk.Manager initialPing func(r *RegistrySQL) error } var _ Registry = new(RegistrySQL) // defaultInitialPing is the default function that will be called within RegistrySQL.Init to make sure // the database is reachable. It can be injected for test purposes by changing the value // of RegistrySQL.initialPing. var defaultInitialPing = func(m *RegistrySQL) error { if err := resilience.Retry(m.l, 5*time.Second, 5*time.Minute, m.Ping); err != nil { m.Logger().Print("Could not ping database: ", err) return errorsx.WithStack(err) } return nil } func init() { dbal.RegisterDriver( func() dbal.Driver { return NewRegistrySQL() }, ) } func NewRegistrySQL() *RegistrySQL { r := &RegistrySQL{ RegistryBase: new(RegistryBase), initialPing: defaultInitialPing, } r.RegistryBase.with(r) return r } func (m *RegistrySQL) Init( ctx context.Context, skipNetworkInit bool, migrate bool, ctxer contextx.Contextualizer, extraMigrations []fs.FS, goMigrations []popx.Migration, ) error { if m.persister == nil { m.WithContextualizer(ctxer) var opts []instrumentedsql.Opt if m.Tracer(ctx).IsLoaded() { opts = []instrumentedsql.Opt{ instrumentedsql.WithTracer(otelsql.NewTracer()), instrumentedsql.WithOmitArgs(), // don't risk leaking PII or secrets instrumentedsql.WithOpsExcluded(instrumentedsql.OpSQLRowsNext), } } // new db connection pool, idlePool, connMaxLifetime, connMaxIdleTime, cleanedDSN := sqlcon.ParseConnectionOptions( m.l, m.Config().DSN(), ) c, err := pop.NewConnection( &pop.ConnectionDetails{ URL: sqlcon.FinalizeDSN(m.l, cleanedDSN), IdlePool: idlePool, ConnMaxLifetime: connMaxLifetime, ConnMaxIdleTime: connMaxIdleTime, Pool: pool, UseInstrumentedDriver: m.Tracer(ctx).IsLoaded(), InstrumentedDriverOptions: opts, Unsafe: m.Config().DbIgnoreUnknownTableColumns(), }, ) if err != nil { return errorsx.WithStack(err) } if err := resilience.Retry(m.l, 5*time.Second, 5*time.Minute, c.Open); err != nil { return errorsx.WithStack(err) } p, err := sql.NewPersister(ctx, c, m, m.Config(), extraMigrations, goMigrations) if err != nil { return err } m.persister = p if err := m.initialPing(m); err != nil { return err } if m.Config().HSMEnabled() { hardwareKeyManager := hsm.NewKeyManager(m.HSMContext(), m.Config()) m.defaultKeyManager = jwk.NewManagerStrategy(hardwareKeyManager, m.persister) } else { m.defaultKeyManager = m.persister } // if dsn is memory we have to run the migrations on every start // use case - such as // - just in memory // - shared connection // - shared but unique in the same process // see: https://sqlite.org/inmemorydb.html if dbal.IsMemorySQLite(m.Config().DSN()) { m.Logger().Print("Hydra is running migrations on every startup as DSN is memory.\n") m.Logger().Print("This means your data is lost when Hydra terminates.\n") if err := p.MigrateUp(context.Background()); err != nil { return err } } else if migrate { if err := p.MigrateUp(context.Background()); err != nil { return err } } if skipNetworkInit { m.persister = p } else { net, err := p.DetermineNetwork(ctx) if err != nil { m.Logger().WithError(err).Warnf("Unable to determine network, retrying.") return err } m.persister = p.WithFallbackNetworkID(net.ID) } if m.Config().HSMEnabled() { hardwareKeyManager := hsm.NewKeyManager(m.HSMContext(), m.Config()) m.defaultKeyManager = jwk.NewManagerStrategy(hardwareKeyManager, m.persister) } else { m.defaultKeyManager = m.persister } } return nil } func (m *RegistrySQL) alwaysCanHandle(dsn string) bool { scheme := strings.Split(dsn, "://")[0] s := dbal.Canonicalize(scheme) return s == dbal.DriverMySQL || s == dbal.DriverPostgreSQL || s == dbal.DriverCockroachDB } func (m *RegistrySQL) Ping() error { return m.Persister().Ping() } func (m *RegistrySQL) ClientManager() client.Manager { return m.Persister() } func (m *RegistrySQL) ConsentManager() consent.Manager { return m.Persister() } func (m *RegistrySQL) OAuth2Storage() x.FositeStorer { return m.Persister() } func (m *RegistrySQL) KeyManager() jwk.Manager { return m.defaultKeyManager } func (m *RegistrySQL) SoftwareKeyManager() jwk.Manager { return m.Persister() } func (m *RegistrySQL) GrantManager() trust.GrantManager { return m.Persister() }
Go
hydra/driver/registry_sqlite.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 //go:build sqlite // +build sqlite package driver import ( "strings" ) func (m *RegistrySQL) CanHandle(dsn string) bool { scheme := strings.Split(dsn, "://")[0] return scheme == "sqlite" || scheme == "sqlite3" || m.alwaysCanHandle(dsn) }
Go
hydra/driver/registry_sql_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package driver import ( "context" "math/rand" "strconv" "testing" "github.com/stretchr/testify/require" "github.com/stretchr/testify/assert" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/driver/config" "github.com/ory/hydra/v2/persistence/sql" "github.com/ory/x/configx" "github.com/ory/x/contextx" "github.com/ory/x/errorsx" "github.com/ory/x/logrusx" "github.com/ory/x/sqlcon/dockertest" ) func TestDefaultKeyManager_HsmDisabled(t *testing.T) { l := logrusx.New("", "") c := config.MustNew(context.Background(), l, configx.SkipValidation()) c.MustSet(context.Background(), config.KeyDSN, "postgres://user:[email protected]:9999/postgres") c.MustSet(context.Background(), config.HSMEnabled, "false") reg, err := NewRegistryWithoutInit(c, l) r := reg.(*RegistrySQL) r.initialPing = sussessfulPing() if err := r.Init(context.Background(), true, false, &contextx.Default{}, nil, nil); err != nil { t.Fatalf("unable to init registry: %s", err) } assert.NoError(t, err) assert.IsType(t, &sql.Persister{}, reg.KeyManager()) assert.IsType(t, &sql.Persister{}, reg.SoftwareKeyManager()) } func TestDbUnknownTableColumns(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") c := config.MustNew(ctx, l, configx.SkipValidation()) postgresDsn := dockertest.RunTestPostgreSQL(t) c.MustSet(ctx, config.KeyDSN, postgresDsn) reg, err := NewRegistryFromDSN(ctx, c, l, false, true, &contextx.Default{}) require.NoError(t, err) statement := "ALTER TABLE \"hydra_client\" ADD COLUMN \"temp_column\" VARCHAR(128) NOT NULL DEFAULT '';" require.NoError(t, reg.Persister().Connection(ctx).RawQuery(statement).Exec()) cl := &client.Client{ LegacyClientID: strconv.Itoa(rand.Int()), } require.NoError(t, reg.Persister().CreateClient(ctx, cl)) getClients := func(reg Registry) ([]client.Client, error) { readClients := make([]client.Client, 0) return readClients, reg.Persister().Connection(ctx).RawQuery("SELECT * FROM \"hydra_client\"").All(&readClients) } t.Run("with ignore disabled (default behavior)", func(t *testing.T) { _, err := getClients(reg) require.Error(t, err) assert.Contains(t, err.Error(), "missing destination name temp_column") }) t.Run("with ignore enabled", func(t *testing.T) { c.MustSet(ctx, config.KeyDBIgnoreUnknownTableColumns, true) reg, err := NewRegistryFromDSN(ctx, c, l, false, true, &contextx.Default{}) require.NoError(t, err) actual, err := getClients(reg) require.NoError(t, err) assert.Len(t, actual, 1) }) } func sussessfulPing() func(r *RegistrySQL) error { return func(r *RegistrySQL) error { // fake that ping is successful return nil } } func failedPing(err error) func(r *RegistrySQL) error { return func(r *RegistrySQL) error { r.Logger().Fatalf(err.Error()) return errorsx.WithStack(err) } }
Go
hydra/driver/config/buildinfo.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config var ( Version = "master" Date = "undefined" Commit = "undefined" )
Go
hydra/driver/config/config.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config type Provider interface { Config() *DefaultProvider }
Go
hydra/driver/config/helper.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "context" "net/url" "github.com/pkg/errors" "github.com/ory/x/logrusx" ) func Validate(ctx context.Context, l *logrusx.Logger, p *DefaultProvider) error { if p.IssuerURL(ctx).String() == "" && !p.IsDevelopmentMode(ctx) { l.Errorf("Configuration key `%s` must be set `dev` is `false`. To find out more, use `hydra help serve`.", KeyIssuerURL) return errors.New("issuer URL must be set unless development mode is enabled") } if p.IssuerURL(ctx).Scheme != "https" && !p.IsDevelopmentMode(ctx) { l.Errorf("Scheme from configuration key `%s` must be `https` when `dev` is `false`. Got scheme in value `%s` is `%s`. To find out more, use `hydra help serve`.", KeyIssuerURL, p.IssuerURL(ctx).String(), p.IssuerURL(ctx).Scheme) return errors.New("issuer URL scheme must be HTTPS unless development mode is enabled") } return nil } func urlRoot(u *url.URL) *url.URL { if u.Path == "" { u.Path = "/" } return u }
Go
hydra/driver/config/provider.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "context" "fmt" "net/http" "net/url" "strings" "time" "github.com/pkg/errors" "github.com/ory/x/hasherx" "github.com/gofrs/uuid" "github.com/ory/x/otelx" "github.com/ory/hydra/v2/spec" "github.com/ory/x/dbal" "github.com/ory/x/configx" "github.com/ory/x/logrusx" "github.com/ory/hydra/v2/x" "github.com/ory/x/contextx" "github.com/ory/x/stringslice" "github.com/ory/x/urlx" ) const ( KeyRoot = "" HSMEnabled = "hsm.enabled" HSMLibraryPath = "hsm.library" HSMPin = "hsm.pin" HSMSlotNumber = "hsm.slot" HSMKeySetPrefix = "hsm.key_set_prefix" HSMTokenLabel = "hsm.token_label" // #nosec G101 KeyWellKnownKeys = "webfinger.jwks.broadcast_keys" KeyOAuth2ClientRegistrationURL = "webfinger.oidc_discovery.client_registration_url" KeyOAuth2TokenURL = "webfinger.oidc_discovery.token_url" // #nosec G101 KeyOAuth2AuthURL = "webfinger.oidc_discovery.auth_url" KeyVerifiableCredentialsURL = "webfinger.oidc_discovery.verifiable_credentials_url" // #nosec G101 KeyJWKSURL = "webfinger.oidc_discovery.jwks_url" KeyOIDCDiscoverySupportedClaims = "webfinger.oidc_discovery.supported_claims" KeyOIDCDiscoverySupportedScope = "webfinger.oidc_discovery.supported_scope" KeyOIDCDiscoveryUserinfoEndpoint = "webfinger.oidc_discovery.userinfo_url" KeySubjectTypesSupported = "oidc.subject_identifiers.supported_types" KeyDefaultClientScope = "oidc.dynamic_client_registration.default_scope" KeyDSN = "dsn" KeyClientHTTPNoPrivateIPRanges = "clients.http.disallow_private_ip_ranges" KeyClientHTTPPrivateIPExceptionURLs = "clients.http.private_ip_exception_urls" KeyHasherAlgorithm = "oauth2.hashers.algorithm" KeyBCryptCost = "oauth2.hashers.bcrypt.cost" KeyPBKDF2Iterations = "oauth2.hashers.pbkdf2.iterations" KeyEncryptSessionData = "oauth2.session.encrypt_at_rest" KeyCookieSameSiteMode = "serve.cookies.same_site_mode" KeyCookieSameSiteLegacyWorkaround = "serve.cookies.same_site_legacy_workaround" KeyCookieDomain = "serve.cookies.domain" KeyCookieSecure = "serve.cookies.secure" KeyCookieLoginCSRFName = "serve.cookies.names.login_csrf" KeyCookieConsentCSRFName = "serve.cookies.names.consent_csrf" KeyCookieSessionName = "serve.cookies.names.session" KeyCookieSessionPath = "serve.cookies.paths.session" KeyConsentRequestMaxAge = "ttl.login_consent_request" KeyAccessTokenLifespan = "ttl.access_token" // #nosec G101 KeyRefreshTokenLifespan = "ttl.refresh_token" // #nosec G101 KeyVerifiableCredentialsNonceLifespan = "ttl.vc_nonce" // #nosec G101 KeyIDTokenLifespan = "ttl.id_token" // #nosec G101 KeyAuthCodeLifespan = "ttl.auth_code" KeyScopeStrategy = "strategies.scope" KeyGetCookieSecrets = "secrets.cookie" KeyGetSystemSecret = "secrets.system" KeyLogoutRedirectURL = "urls.post_logout_redirect" KeyLoginURL = "urls.login" KeyLogoutURL = "urls.logout" KeyConsentURL = "urls.consent" KeyErrorURL = "urls.error" KeyPublicURL = "urls.self.public" KeyAdminURL = "urls.self.admin" KeyIssuerURL = "urls.self.issuer" KeyIdentityProviderAdminURL = "urls.identity_provider.url" KeyIdentityProviderHeaders = "urls.identity_provider.headers" KeyAccessTokenStrategy = "strategies.access_token" KeyJWTScopeClaimStrategy = "strategies.jwt.scope_claim" KeyDBIgnoreUnknownTableColumns = "db.ignore_unknown_table_columns" KeySubjectIdentifierAlgorithmSalt = "oidc.subject_identifiers.pairwise.salt" KeyPublicAllowDynamicRegistration = "oidc.dynamic_client_registration.enabled" KeyPKCEEnforced = "oauth2.pkce.enforced" KeyPKCEEnforcedForPublicClients = "oauth2.pkce.enforced_for_public_clients" KeyLogLevel = "log.level" KeyCGroupsV1AutoMaxProcsEnabled = "cgroups.v1.auto_max_procs_enabled" KeyGrantAllClientCredentialsScopesPerDefault = "oauth2.client_credentials.default_grant_allowed_scope" // #nosec G101 KeyExposeOAuth2Debug = "oauth2.expose_internal_errors" KeyExcludeNotBeforeClaim = "oauth2.exclude_not_before_claim" KeyAllowedTopLevelClaims = "oauth2.allowed_top_level_claims" KeyMirrorTopLevelClaims = "oauth2.mirror_top_level_claims" KeyOAuth2GrantJWTIDOptional = "oauth2.grant.jwt.jti_optional" KeyOAuth2GrantJWTIssuedDateOptional = "oauth2.grant.jwt.iat_optional" KeyOAuth2GrantJWTMaxDuration = "oauth2.grant.jwt.max_ttl" KeyRefreshTokenHookURL = "oauth2.refresh_token_hook" // #nosec G101 KeyTokenHookURL = "oauth2.token_hook" // #nosec G101 KeyDevelopmentMode = "dev" ) const DSNMemory = "memory" var ( _ hasherx.PBKDF2Configurator = (*DefaultProvider)(nil) _ hasherx.BCryptConfigurator = (*DefaultProvider)(nil) ) type DefaultProvider struct { l *logrusx.Logger p *configx.Provider c contextx.Contextualizer } func (p *DefaultProvider) GetHasherAlgorithm(ctx context.Context) x.HashAlgorithm { switch strings.ToLower(p.getProvider(ctx).String(KeyHasherAlgorithm)) { case x.HashAlgorithmBCrypt.String(): return x.HashAlgorithmBCrypt case x.HashAlgorithmPBKDF2.String(): fallthrough default: return x.HashAlgorithmPBKDF2 } } func (p *DefaultProvider) HasherBcryptConfig(ctx context.Context) *hasherx.BCryptConfig { return &hasherx.BCryptConfig{ Cost: uint32(p.GetBCryptCost(ctx)), } } func (p *DefaultProvider) HasherPBKDF2Config(ctx context.Context) *hasherx.PBKDF2Config { return &hasherx.PBKDF2Config{ Algorithm: "sha256", Iterations: uint32(p.getProvider(ctx).Int(KeyPBKDF2Iterations)), SaltLength: 16, KeyLength: 32, } } func MustNew(ctx context.Context, l *logrusx.Logger, opts ...configx.OptionModifier) *DefaultProvider { p, err := New(ctx, l, opts...) if err != nil { l.WithError(err).Fatalf("Unable to load config.") } return p } func (p *DefaultProvider) getProvider(ctx context.Context) *configx.Provider { return p.c.Config(ctx, p.p) } func New(ctx context.Context, l *logrusx.Logger, opts ...configx.OptionModifier) (*DefaultProvider, error) { opts = append( []configx.OptionModifier{ configx.WithStderrValidationReporter(), configx.OmitKeysFromTracing("dsn", "secrets.system", "secrets.cookie"), configx.WithImmutables("log", "serve", "dsn", "profiling"), configx.WithLogrusWatcher(l), }, opts..., ) p, err := configx.New(ctx, spec.ConfigValidationSchema, opts...) if err != nil { return nil, err } return NewCustom(l, p, &contextx.Default{}), nil } func NewCustom(l *logrusx.Logger, p *configx.Provider, ctxt contextx.Contextualizer) *DefaultProvider { l.UseConfig(p) return &DefaultProvider{l: l, p: p, c: ctxt} } func (p *DefaultProvider) Set(ctx context.Context, key string, value interface{}) error { return p.getProvider(ctx).Set(key, value) } func (p *DefaultProvider) MustSet(ctx context.Context, key string, value interface{}) { if err := p.Set(ctx, key, value); err != nil { p.l.WithError(err).Fatalf("Unable to set \"%s\" to \"%s\".", key, value) } } func (p *DefaultProvider) Source(ctx context.Context) *configx.Provider { return p.getProvider(ctx) } func (p *DefaultProvider) IsDevelopmentMode(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyDevelopmentMode) } func (p *DefaultProvider) WellKnownKeys(ctx context.Context, include ...string) []string { include = append(include, x.OAuth2JWTKeyName, x.OpenIDConnectKeyName) return stringslice.Unique(append(p.getProvider(ctx).Strings(KeyWellKnownKeys), include...)) } func (p *DefaultProvider) ClientHTTPNoPrivateIPRanges() bool { return p.getProvider(contextx.RootContext).Bool(KeyClientHTTPNoPrivateIPRanges) } func (p *DefaultProvider) ClientHTTPPrivateIPExceptionURLs() []string { return p.getProvider(contextx.RootContext).Strings(KeyClientHTTPPrivateIPExceptionURLs) } func (p *DefaultProvider) AllowedTopLevelClaims(ctx context.Context) []string { return stringslice.Unique(p.getProvider(ctx).Strings(KeyAllowedTopLevelClaims)) } func (p *DefaultProvider) MirrorTopLevelClaims(ctx context.Context) bool { return p.getProvider(ctx).BoolF(KeyMirrorTopLevelClaims, true) } func (p *DefaultProvider) SubjectTypesSupported(ctx context.Context, additionalSources ...AccessTokenStrategySource) []string { types := stringslice.Filter( p.getProvider(ctx).StringsF(KeySubjectTypesSupported, []string{"public"}), func(s string) bool { return !(s == "public" || s == "pairwise") }, ) if len(types) == 0 { types = []string{"public"} } if stringslice.Has(types, "pairwise") { if p.AccessTokenStrategy(ctx, additionalSources...) == AccessTokenJWTStrategy { p.l.Warn(`The pairwise subject identifier algorithm is not supported by the JWT OAuth 2.0 Access Token Strategy and is thus being disabled. Please remove "pairwise" from oidc.subject_identifiers.supported_types" (e.g. oidc.subject_identifiers.supported_types=public) or set strategies.access_token to "opaque".`) types = stringslice.Filter( types, func(s string) bool { return !(s == "public") }, ) } else if len(p.SubjectIdentifierAlgorithmSalt(ctx)) < 8 { p.l.Fatalf( `The pairwise subject identifier algorithm was set but length of oidc.subject_identifier.salt is too small (%d < 8), please set oidc.subject_identifiers.pairwise.salt to a random string with 8 characters or more.`, len(p.SubjectIdentifierAlgorithmSalt(ctx)), ) } } return types } func (p *DefaultProvider) DefaultClientScope(ctx context.Context) []string { return p.getProvider(ctx).StringsF( KeyDefaultClientScope, []string{"offline_access", "offline", "openid"}, ) } func (p *DefaultProvider) DSN() string { dsn := p.getProvider(contextx.RootContext).String(KeyDSN) if dsn == DSNMemory { return dbal.NewSQLiteInMemoryDatabase(uuid.Must(uuid.NewV4()).String()) } if len(dsn) > 0 { return dsn } p.l.Fatal("dsn must be set") return "" } func (p *DefaultProvider) EncryptSessionData(ctx context.Context) bool { return p.getProvider(ctx).BoolF(KeyEncryptSessionData, true) } func (p *DefaultProvider) ExcludeNotBeforeClaim(ctx context.Context) bool { return p.getProvider(ctx).BoolF(KeyExcludeNotBeforeClaim, false) } func (p *DefaultProvider) CookieSecure(ctx context.Context) bool { if !p.IsDevelopmentMode(ctx) { return true } return p.getProvider(ctx).BoolF(KeyCookieSecure, false) } func (p *DefaultProvider) CookieSameSiteMode(ctx context.Context) http.SameSite { sameSiteModeStr := p.getProvider(ctx).String(KeyCookieSameSiteMode) switch strings.ToLower(sameSiteModeStr) { case "lax": return http.SameSiteLaxMode case "strict": return http.SameSiteStrictMode case "none": if p.IssuerURL(ctx).Scheme != "https" { // SameSite=None can only be set for HTTPS issuers. return http.SameSiteLaxMode } return http.SameSiteNoneMode default: if p.IsDevelopmentMode(ctx) { return http.SameSiteLaxMode } return http.SameSiteDefaultMode } } func (p *DefaultProvider) PublicAllowDynamicRegistration(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyPublicAllowDynamicRegistration) } func (p *DefaultProvider) CookieSameSiteLegacyWorkaround(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyCookieSameSiteLegacyWorkaround) } func (p *DefaultProvider) ConsentRequestMaxAge(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyConsentRequestMaxAge, time.Minute*30) } func (p *DefaultProvider) Tracing() *otelx.Config { return p.getProvider(contextx.RootContext).TracingConfig("Ory Hydra") } func (p *DefaultProvider) GetCookieSecrets(ctx context.Context) ([][]byte, error) { secrets := p.getProvider(ctx).Strings(KeyGetCookieSecrets) if len(secrets) == 0 { secret, err := p.GetGlobalSecret(ctx) if err != nil { return nil, err } return [][]byte{secret}, nil } bs := make([][]byte, len(secrets)) for k := range secrets { bs[k] = []byte(secrets[k]) } return bs, nil } func (p *DefaultProvider) LogoutRedirectURL(ctx context.Context) *url.URL { return urlRoot( p.getProvider(ctx).RequestURIF( KeyLogoutRedirectURL, p.publicFallbackURL(ctx, "oauth2/fallbacks/logout/callback"), ), ) } func (p *DefaultProvider) publicFallbackURL(ctx context.Context, path string) *url.URL { if len(p.PublicURL(ctx).String()) > 0 { return urlx.AppendPaths(p.PublicURL(ctx), path) } return p.fallbackURL(ctx, path, p.host(PublicInterface), p.port(PublicInterface)) } func (p *DefaultProvider) fallbackURL(ctx context.Context, path string, host string, port int) *url.URL { var u url.URL u.Scheme = "http" if tls := p.TLS(ctx, PublicInterface); tls.Enabled() || !p.IsDevelopmentMode(ctx) { u.Scheme = "https" } if host == "" { u.Host = fmt.Sprintf("%s:%d", "localhost", port) } u.Path = path return &u } func (p *DefaultProvider) LoginURL(ctx context.Context) *url.URL { return urlRoot(p.getProvider(ctx).URIF(KeyLoginURL, p.publicFallbackURL(ctx, "oauth2/fallbacks/login"))) } func (p *DefaultProvider) LogoutURL(ctx context.Context) *url.URL { return urlRoot(p.getProvider(ctx).RequestURIF(KeyLogoutURL, p.publicFallbackURL(ctx, "oauth2/fallbacks/logout"))) } func (p *DefaultProvider) ConsentURL(ctx context.Context) *url.URL { return urlRoot(p.getProvider(ctx).URIF(KeyConsentURL, p.publicFallbackURL(ctx, "oauth2/fallbacks/consent"))) } func (p *DefaultProvider) ErrorURL(ctx context.Context) *url.URL { return urlRoot(p.getProvider(ctx).RequestURIF(KeyErrorURL, p.publicFallbackURL(ctx, "oauth2/fallbacks/error"))) } func (p *DefaultProvider) PublicURL(ctx context.Context) *url.URL { return urlRoot(p.getProvider(ctx).RequestURIF(KeyPublicURL, p.IssuerURL(ctx))) } func (p *DefaultProvider) AdminURL(ctx context.Context) *url.URL { return urlRoot( p.getProvider(ctx).RequestURIF( KeyAdminURL, p.fallbackURL(ctx, "/", p.host(AdminInterface), p.port(AdminInterface)), ), ) } func (p *DefaultProvider) IssuerURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF( KeyIssuerURL, p.fallbackURL(ctx, "/", p.host(PublicInterface), p.port(PublicInterface)), ) } func (p *DefaultProvider) KratosAdminURL(ctx context.Context) (*url.URL, bool) { u := p.getProvider(ctx).RequestURIF(KeyIdentityProviderAdminURL, nil) return u, u != nil } func (p *DefaultProvider) KratosRequestHeader(ctx context.Context) http.Header { hh := map[string]string{} if err := p.getProvider(ctx).Unmarshal(KeyIdentityProviderHeaders, &hh); err != nil { p.l.WithError(errors.WithStack(err)). Errorf("Configuration value from key %s could not be decoded.", KeyIdentityProviderHeaders) return nil } h := make(http.Header) for k, v := range hh { h.Set(k, v) } return h } func (p *DefaultProvider) OAuth2ClientRegistrationURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyOAuth2ClientRegistrationURL, new(url.URL)) } func (p *DefaultProvider) OAuth2TokenURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyOAuth2TokenURL, urlx.AppendPaths(p.PublicURL(ctx), "/oauth2/token")) } func (p *DefaultProvider) OAuth2AuthURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyOAuth2AuthURL, urlx.AppendPaths(p.PublicURL(ctx), "/oauth2/auth")) } func (p *DefaultProvider) JWKSURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyJWKSURL, urlx.AppendPaths(p.IssuerURL(ctx), "/.well-known/jwks.json")) } func (p *DefaultProvider) CredentialsEndpointURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyVerifiableCredentialsURL, urlx.AppendPaths(p.PublicURL(ctx), "/credentials")) } type AccessTokenStrategySource interface { GetAccessTokenStrategy() AccessTokenStrategyType } func (p *DefaultProvider) AccessTokenStrategy(ctx context.Context, additionalSources ...AccessTokenStrategySource) AccessTokenStrategyType { for _, src := range additionalSources { if src == nil { continue } if strategy := src.GetAccessTokenStrategy(); strategy != "" { return strategy } } s, err := ToAccessTokenStrategyType(p.getProvider(ctx).String(KeyAccessTokenStrategy)) if err != nil { p.l.WithError(err).Warn("Key `strategies.access_token` contains an invalid value, falling back to `opaque` strategy.") return AccessTokenDefaultStrategy } return s } func (p *DefaultProvider) TokenHookURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyTokenHookURL, nil) } func (p *DefaultProvider) TokenRefreshHookURL(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF(KeyRefreshTokenHookURL, nil) } func (p *DefaultProvider) DbIgnoreUnknownTableColumns() bool { return p.p.Bool(KeyDBIgnoreUnknownTableColumns) } func (p *DefaultProvider) SubjectIdentifierAlgorithmSalt(ctx context.Context) string { return p.getProvider(ctx).String(KeySubjectIdentifierAlgorithmSalt) } func (p *DefaultProvider) OIDCDiscoverySupportedClaims(ctx context.Context) []string { return stringslice.Unique( append( []string{"sub"}, p.getProvider(ctx).Strings(KeyOIDCDiscoverySupportedClaims)..., ), ) } func (p *DefaultProvider) OIDCDiscoverySupportedScope(ctx context.Context) []string { return stringslice.Unique( append( []string{"offline_access", "offline", "openid"}, p.getProvider(ctx).Strings(KeyOIDCDiscoverySupportedScope)..., ), ) } func (p *DefaultProvider) OIDCDiscoveryUserinfoEndpoint(ctx context.Context) *url.URL { return p.getProvider(ctx).RequestURIF( KeyOIDCDiscoveryUserinfoEndpoint, urlx.AppendPaths(p.PublicURL(ctx), "/userinfo"), ) } func (p *DefaultProvider) GetSendDebugMessagesToClients(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyExposeOAuth2Debug) } func (p *DefaultProvider) GetEnforcePKCE(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyPKCEEnforced) } func (p *DefaultProvider) GetEnforcePKCEForPublicClients(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyPKCEEnforcedForPublicClients) } func (p *DefaultProvider) CGroupsV1AutoMaxProcsEnabled() bool { return p.getProvider(contextx.RootContext).Bool(KeyCGroupsV1AutoMaxProcsEnabled) } func (p *DefaultProvider) GrantAllClientCredentialsScopesPerDefault(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyGrantAllClientCredentialsScopesPerDefault) } func (p *DefaultProvider) HSMEnabled() bool { return p.getProvider(contextx.RootContext).Bool(HSMEnabled) } func (p *DefaultProvider) HSMLibraryPath() string { return p.getProvider(contextx.RootContext).String(HSMLibraryPath) } func (p *DefaultProvider) HSMSlotNumber() *int { n := p.getProvider(contextx.RootContext).Int(HSMSlotNumber) return &n } func (p *DefaultProvider) HSMPin() string { return p.getProvider(contextx.RootContext).String(HSMPin) } func (p *DefaultProvider) HSMTokenLabel() string { return p.getProvider(contextx.RootContext).String(HSMTokenLabel) } func (p *DefaultProvider) GetGrantTypeJWTBearerIDOptional(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyOAuth2GrantJWTIDOptional) } func (p *DefaultProvider) HSMKeySetPrefix() string { return p.getProvider(contextx.RootContext).String(HSMKeySetPrefix) } func (p *DefaultProvider) GetGrantTypeJWTBearerIssuedDateOptional(ctx context.Context) bool { return p.getProvider(ctx).Bool(KeyOAuth2GrantJWTIssuedDateOptional) } func (p *DefaultProvider) GetJWTMaxDuration(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyOAuth2GrantJWTMaxDuration, time.Hour*24*30) } func (p *DefaultProvider) CookieDomain(ctx context.Context) string { return p.getProvider(ctx).String(KeyCookieDomain) } func (p *DefaultProvider) SessionCookiePath(ctx context.Context) string { return p.getProvider(ctx).StringF(KeyCookieSessionPath, "/") } func (p *DefaultProvider) CookieNameLoginCSRF(ctx context.Context) string { return p.cookieSuffix(ctx, KeyCookieLoginCSRFName) } func (p *DefaultProvider) CookieNameConsentCSRF(ctx context.Context) string { return p.cookieSuffix(ctx, KeyCookieConsentCSRFName) } func (p *DefaultProvider) SessionCookieName(ctx context.Context) string { return p.cookieSuffix(ctx, KeyCookieSessionName) } func (p *DefaultProvider) cookieSuffix(ctx context.Context, key string) string { var suffix string if p.IsDevelopmentMode(ctx) { suffix = "_dev" } return p.getProvider(ctx).String(key) + suffix }
Go
hydra/driver/config/provider_fosite.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "context" "strings" "time" "github.com/pkg/errors" "github.com/ory/fosite" "github.com/ory/fosite/token/jwt" "github.com/ory/hydra/v2/x" ) var _ fosite.GlobalSecretProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetGlobalSecret(ctx context.Context) ([]byte, error) { secrets := p.getProvider(ctx).Strings(KeyGetSystemSecret) if len(secrets) == 0 { p.l.Error("The system secret is not configured. Please provide one in the configuration file or environment variables.") return nil, errors.New("global secret is not configured") } secret := secrets[0] if len(secret) < 16 { p.l.Errorf("System secret must be undefined or have at least 16 characters but only has %d characters.", len(secret)) return nil, errors.New("global secret is too short") } return x.HashStringSecret(secret), nil } var _ fosite.RotatedGlobalSecretsProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetRotatedGlobalSecrets(ctx context.Context) ([][]byte, error) { secrets := p.getProvider(ctx).Strings(KeyGetSystemSecret) if len(secrets) < 2 { return nil, nil } var rotated [][]byte for _, secret := range secrets[1:] { rotated = append(rotated, x.HashStringSecret(secret)) } return rotated, nil } var _ fosite.BCryptCostProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetBCryptCost(ctx context.Context) int { return p.getProvider(ctx).IntF(KeyBCryptCost, 10) } var _ fosite.AccessTokenLifespanProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetAccessTokenLifespan(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyAccessTokenLifespan, time.Hour) } var _ fosite.RefreshTokenLifespanProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetRefreshTokenLifespan(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyRefreshTokenLifespan, time.Hour*720) } var _ fosite.VerifiableCredentialsNonceLifespanProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetVerifiableCredentialsNonceLifespan(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyVerifiableCredentialsNonceLifespan, time.Hour) } var _ fosite.IDTokenLifespanProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetIDTokenLifespan(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyIDTokenLifespan, time.Hour) } var _ fosite.AuthorizeCodeLifespanProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetAuthorizeCodeLifespan(ctx context.Context) time.Duration { return p.getProvider(ctx).DurationF(KeyAuthCodeLifespan, time.Minute*10) } var _ fosite.ScopeStrategyProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetScopeStrategy(ctx context.Context) fosite.ScopeStrategy { if strings.ToLower(p.getProvider(ctx).String(KeyScopeStrategy)) == "wildcard" { return fosite.WildcardScopeStrategy } return fosite.ExactScopeStrategy } var _ fosite.JWTScopeFieldProvider = (*DefaultProvider)(nil) func (p *DefaultProvider) GetJWTScopeField(ctx context.Context) jwt.JWTScopeFieldEnum { switch strings.ToLower(p.getProvider(ctx).String(KeyJWTScopeClaimStrategy)) { case "string": return jwt.JWTScopeFieldString case "both": return jwt.JWTScopeFieldBoth case "list": return jwt.JWTScopeFieldList default: return jwt.JWTScopeFieldUnset } } func (p *DefaultProvider) GetUseLegacyErrorFormat(context.Context) bool { return false }
Go
hydra/driver/config/provider_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "context" "fmt" "io" "net/http" "net/url" "os" "strings" "testing" "time" "github.com/ory/fosite/token/jwt" "github.com/ory/x/configx" "github.com/ory/x/otelx" "github.com/rs/cors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ory/x/urlx" "github.com/ory/x/logrusx" "github.com/ory/hydra/v2/x" ) func newProvider() *DefaultProvider { return MustNew(context.Background(), logrusx.New("", "")) } func setupEnv(env map[string]string) func(t *testing.T) func() { return func(t *testing.T) (setup func()) { setup = func() { for k, v := range env { t.Setenv(k, v) } } return } } func TestSubjectTypesSupported(t *testing.T) { ctx := context.Background() for k, tc := range []struct { d string env func(t *testing.T) func() e []string }{ { d: "Load legacy environment variable in legacy format", env: setupEnv(map[string]string{ strings.ToUpper(strings.Replace(KeySubjectTypesSupported, ".", "_", -1)): "public,pairwise", strings.ToUpper(strings.Replace("oidc.subject_identifiers.pairwise.salt", ".", "_", -1)): "some-salt", }), e: []string{"public", "pairwise"}, }, { d: "Load legacy environment variable in legacy format with JWT enabled", env: setupEnv(map[string]string{ strings.ToUpper(strings.Replace(KeySubjectTypesSupported, ".", "_", -1)): "public,pairwise", strings.ToUpper(strings.Replace("oidc.subject_identifiers.pairwise.salt", ".", "_", -1)): "some-salt", strings.ToUpper(strings.Replace(KeyAccessTokenStrategy, ".", "_", -1)): "jwt", }), e: []string{"public"}, }, } { t.Run(fmt.Sprintf("case=%d/description=%s", k, tc.d), func(t *testing.T) { setup := tc.env(t) setup() p := newProvider() p.MustSet(ctx, KeySubjectIdentifierAlgorithmSalt, "00000000") assert.EqualValues(t, tc.e, p.SubjectTypesSupported(ctx)) }) } } func TestWellKnownKeysUnique(t *testing.T) { p := newProvider() assert.EqualValues(t, []string{x.OpenIDConnectKeyName, x.OAuth2JWTKeyName}, p.WellKnownKeys(context.Background(), x.OAuth2JWTKeyName, x.OpenIDConnectKeyName, x.OpenIDConnectKeyName)) } func TestCORSOptions(t *testing.T) { ctx := context.Background() p := newProvider() p.MustSet(ctx, "serve.public.cors.enabled", true) conf, enabled := p.CORS(ctx, PublicInterface) assert.True(t, enabled) assert.EqualValues(t, cors.Options{ AllowedOrigins: []string{}, AllowedMethods: []string{"POST", "GET", "PUT", "PATCH", "DELETE", "CONNECT", "HEAD", "OPTIONS", "TRACE"}, AllowedHeaders: []string{"Accept", "Content-Type", "Content-Length", "Accept-Language", "Content-Language", "Authorization"}, ExposedHeaders: []string{"Cache-Control", "Expires", "Last-Modified", "Pragma", "Content-Length", "Content-Language", "Content-Type"}, AllowCredentials: true, }, conf) } func TestProviderAdminDisableHealthAccessLog(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) value := p.DisableHealthAccessLog(AdminInterface) assert.Equal(t, false, value) p.MustSet(ctx, AdminInterface.Key(KeySuffixDisableHealthAccessLog), "true") value = p.DisableHealthAccessLog(AdminInterface) assert.Equal(t, true, value) } func TestProviderPublicDisableHealthAccessLog(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) value := p.DisableHealthAccessLog(PublicInterface) assert.Equal(t, false, value) p.MustSet(ctx, PublicInterface.Key(KeySuffixDisableHealthAccessLog), "true") value = p.DisableHealthAccessLog(PublicInterface) assert.Equal(t, true, value) } func TestPublicAllowDynamicRegistration(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) value := p.PublicAllowDynamicRegistration(ctx) assert.Equal(t, false, value) p.MustSet(ctx, KeyPublicAllowDynamicRegistration, "true") value = p.PublicAllowDynamicRegistration(ctx) assert.Equal(t, true, value) } func TestProviderIssuerURL(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) p.MustSet(ctx, KeyIssuerURL, "http://hydra.localhost") assert.Equal(t, "http://hydra.localhost", p.IssuerURL(ctx).String()) p2 := MustNew(context.Background(), l) p2.MustSet(ctx, KeyIssuerURL, "http://hydra.localhost/") assert.Equal(t, "http://hydra.localhost/", p2.IssuerURL(ctx).String()) } func TestProviderIssuerPublicURL(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) p.MustSet(ctx, KeyIssuerURL, "http://hydra.localhost") p.MustSet(ctx, KeyPublicURL, "http://hydra.example") assert.Equal(t, "http://hydra.localhost", p.IssuerURL(ctx).String()) assert.Equal(t, "http://hydra.example/", p.PublicURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/.well-known/jwks.json", p.JWKSURL(ctx).String()) assert.Equal(t, "http://hydra.example/oauth2/fallbacks/consent", p.ConsentURL(ctx).String()) assert.Equal(t, "http://hydra.example/oauth2/fallbacks/login", p.LoginURL(ctx).String()) assert.Equal(t, "http://hydra.example/oauth2/fallbacks/logout", p.LogoutURL(ctx).String()) assert.Equal(t, "http://hydra.example/oauth2/token", p.OAuth2TokenURL(ctx).String()) assert.Equal(t, "http://hydra.example/oauth2/auth", p.OAuth2AuthURL(ctx).String()) assert.Equal(t, "http://hydra.example/userinfo", p.OIDCDiscoveryUserinfoEndpoint(ctx).String()) p2 := MustNew(context.Background(), l) p2.MustSet(ctx, KeyIssuerURL, "http://hydra.localhost/") assert.Equal(t, "http://hydra.localhost/", p2.IssuerURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/", p2.PublicURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/.well-known/jwks.json", p2.JWKSURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/oauth2/fallbacks/consent", p2.ConsentURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/oauth2/fallbacks/login", p2.LoginURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/oauth2/fallbacks/logout", p2.LogoutURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/oauth2/token", p2.OAuth2TokenURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/oauth2/auth", p2.OAuth2AuthURL(ctx).String()) assert.Equal(t, "http://hydra.localhost/userinfo", p2.OIDCDiscoveryUserinfoEndpoint(ctx).String()) } func TestProviderCookieSameSiteMode(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l, configx.SkipValidation()) p.MustSet(ctx, KeyTLSEnabled, true) p.MustSet(ctx, KeyCookieSameSiteMode, "") assert.Equal(t, http.SameSiteDefaultMode, p.CookieSameSiteMode(ctx)) p.MustSet(ctx, KeyCookieSameSiteMode, "none") assert.Equal(t, http.SameSiteNoneMode, p.CookieSameSiteMode(ctx)) p.MustSet(ctx, KeyCookieSameSiteMode, "lax") assert.Equal(t, http.SameSiteLaxMode, p.CookieSameSiteMode(ctx)) p.MustSet(ctx, KeyCookieSameSiteMode, "strict") assert.Equal(t, http.SameSiteStrictMode, p.CookieSameSiteMode(ctx)) p = MustNew(context.Background(), l, configx.SkipValidation()) p.MustSet(ctx, "dev", true) assert.Equal(t, http.SameSiteLaxMode, p.CookieSameSiteMode(ctx)) p.MustSet(ctx, KeyCookieSameSiteMode, "none") assert.Equal(t, http.SameSiteLaxMode, p.CookieSameSiteMode(ctx)) p.MustSet(ctx, KeyIssuerURL, "https://example.com") assert.Equal(t, http.SameSiteNoneMode, p.CookieSameSiteMode(ctx)) } func TestViperProviderValidates(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") c := MustNew(context.Background(), l, configx.WithConfigFiles("../../internal/.hydra.yaml")) // log assert.Equal(t, "debug", c.Source(ctx).String(KeyLogLevel)) assert.Equal(t, "json", c.Source(ctx).String("log.format")) // serve assert.Equal(t, "localhost:1", c.ListenOn(PublicInterface)) assert.Equal(t, "localhost:2", c.ListenOn(AdminInterface)) expectedPublicPermission := &configx.UnixPermission{ Owner: "hydra", Group: "hydra-public-api", Mode: 0775, } expectedAdminPermission := &configx.UnixPermission{ Owner: "hydra", Group: "hydra-admin-api", Mode: 0770, } assert.Equal(t, expectedPublicPermission, c.SocketPermission(PublicInterface)) assert.Equal(t, expectedAdminPermission, c.SocketPermission(AdminInterface)) expectedCors := cors.Options{ AllowedOrigins: []string{"https://example.com"}, AllowedMethods: []string{"GET"}, AllowedHeaders: []string{"Authorization"}, ExposedHeaders: []string{"Content-Type"}, AllowCredentials: true, MaxAge: 1, Debug: false, } gc, enabled := c.CORS(ctx, AdminInterface) assert.False(t, enabled) assert.Equal(t, expectedCors, gc) gc, enabled = c.CORS(ctx, PublicInterface) assert.False(t, enabled) assert.Equal(t, expectedCors, gc) assert.Equal(t, []string{"127.0.0.1/32"}, c.TLS(ctx, PublicInterface).AllowTerminationFrom()) assert.Equal(t, "/path/to/file.pem", c.Source(ctx).String("serve.tls.key.path")) assert.Equal(t, "b3J5IGh5ZHJhIGlzIGF3ZXNvbWUK", c.Source(ctx).String("serve.tls.cert.base64")) assert.Equal(t, http.SameSiteLaxMode, c.CookieSameSiteMode(ctx)) assert.Equal(t, true, c.CookieSameSiteLegacyWorkaround(ctx)) // dsn assert.Contains(t, c.DSN(), "sqlite://") // webfinger assert.Equal(t, []string{"hydra.openid.id-token", "hydra.jwt.access-token"}, c.WellKnownKeys(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://example.com"), c.OAuth2ClientRegistrationURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://example.com/jwks.json"), c.JWKSURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://example.com/auth"), c.OAuth2AuthURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://example.com/token"), c.OAuth2TokenURL(ctx)) assert.Equal(t, []string{"sub", "username"}, c.OIDCDiscoverySupportedClaims(ctx)) assert.Equal(t, []string{"offline_access", "offline", "openid", "whatever"}, c.OIDCDiscoverySupportedScope(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://example.com"), c.OIDCDiscoveryUserinfoEndpoint(ctx)) // oidc assert.Equal(t, []string{"pairwise"}, c.SubjectTypesSupported(ctx)) assert.Equal(t, "random_salt", c.SubjectIdentifierAlgorithmSalt(ctx)) assert.Equal(t, []string{"whatever"}, c.DefaultClientScope(ctx)) // urls assert.Equal(t, urlx.ParseOrPanic("https://issuer"), c.IssuerURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://public/"), c.PublicURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://admin/"), c.AdminURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://login/"), c.LoginURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://consent/"), c.ConsentURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://logout/"), c.LogoutURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://error/"), c.ErrorURL(ctx)) assert.Equal(t, urlx.ParseOrPanic("https://post_logout/"), c.LogoutRedirectURL(ctx)) // strategies assert.True(t, c.GetScopeStrategy(ctx)([]string{"openid"}, "openid"), "should us fosite.ExactScopeStrategy") assert.False(t, c.GetScopeStrategy(ctx)([]string{"openid.*"}, "openid.email"), "should us fosite.ExactScopeStrategy") assert.Equal(t, AccessTokenDefaultStrategy, c.AccessTokenStrategy(ctx)) assert.Equal(t, false, c.GrantAllClientCredentialsScopesPerDefault(ctx)) assert.Equal(t, jwt.JWTScopeFieldList, c.GetJWTScopeField(ctx)) // ttl assert.Equal(t, 2*time.Hour, c.ConsentRequestMaxAge(ctx)) assert.Equal(t, 2*time.Hour, c.GetAccessTokenLifespan(ctx)) assert.Equal(t, 2*time.Hour, c.GetRefreshTokenLifespan(ctx)) assert.Equal(t, 2*time.Hour, c.GetIDTokenLifespan(ctx)) assert.Equal(t, 2*time.Hour, c.GetAuthorizeCodeLifespan(ctx)) // oauth2 assert.Equal(t, true, c.GetSendDebugMessagesToClients(ctx)) assert.Equal(t, 20, c.GetBCryptCost(ctx)) assert.Equal(t, true, c.GetEnforcePKCE(ctx)) assert.Equal(t, true, c.GetEnforcePKCEForPublicClients(ctx)) // secrets secret, err := c.GetGlobalSecret(ctx) require.NoError(t, err) assert.Equal(t, []byte{0x64, 0x40, 0x5f, 0xd4, 0x66, 0xc9, 0x8c, 0x88, 0xa7, 0xf2, 0xcb, 0x95, 0xcd, 0x95, 0xcb, 0xa3, 0x41, 0x49, 0x8b, 0x97, 0xba, 0x9e, 0x92, 0xee, 0x4c, 0xaf, 0xe0, 0x71, 0x23, 0x28, 0xeb, 0xfc}, secret) cookieSecret, err := c.GetCookieSecrets(ctx) require.NoError(t, err) assert.Equal(t, [][]uint8{[]byte("some-random-cookie-secret")}, cookieSecret) // profiling assert.Equal(t, "cpu", c.Source(ctx).String("profiling")) // tracing assert.EqualValues(t, &otelx.Config{ ServiceName: "hydra service", Provider: "jaeger", Providers: otelx.ProvidersConfig{ Jaeger: otelx.JaegerConfig{ LocalAgentAddress: "127.0.0.1:6831", Sampling: otelx.JaegerSampling{ ServerURL: "http://sampling", TraceIdRatio: 1, }, }, Zipkin: otelx.ZipkinConfig{ ServerURL: "http://zipkin/api/v2/spans", }, OTLP: otelx.OTLPConfig{ ServerURL: "localhost:4318", Insecure: true, Sampling: otelx.OTLPSampling{ SamplingRatio: 1.0, }, }, }, }, c.Tracing()) } func TestSetPerm(t *testing.T) { f, e := os.CreateTemp("", "test") require.NoError(t, e) path := f.Name() // We cannot test setting owner and group, because we don't know what the // tester has access to. _ = (&configx.UnixPermission{ Owner: "", Group: "", Mode: 0654, }).SetPermission(path) stat, err := f.Stat() require.NoError(t, err) assert.Equal(t, os.FileMode(0654), stat.Mode()) require.NoError(t, f.Close()) require.NoError(t, os.Remove(path)) } func TestLoginConsentURL(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) p.MustSet(ctx, KeyLoginURL, "http://localhost:8080/oauth/login") p.MustSet(ctx, KeyConsentURL, "http://localhost:8080/oauth/consent") assert.Equal(t, "http://localhost:8080/oauth/login", p.LoginURL(ctx).String()) assert.Equal(t, "http://localhost:8080/oauth/consent", p.ConsentURL(ctx).String()) p2 := MustNew(context.Background(), l) p2.MustSet(ctx, KeyLoginURL, "http://localhost:3000/#/oauth/login") p2.MustSet(ctx, KeyConsentURL, "http://localhost:3000/#/oauth/consent") assert.Equal(t, "http://localhost:3000/#/oauth/login", p2.LoginURL(ctx).String()) assert.Equal(t, "http://localhost:3000/#/oauth/consent", p2.ConsentURL(ctx).String()) } func TestInfinitRefreshTokenTTL(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) c := MustNew(context.Background(), l, configx.WithValue("ttl.refresh_token", -1)) assert.Equal(t, -1*time.Nanosecond, c.GetRefreshTokenLifespan(ctx)) } func TestCookieSecure(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) c := MustNew(context.Background(), l, configx.WithValue(KeyDevelopmentMode, true)) c.MustSet(ctx, KeyCookieSecure, true) assert.True(t, c.CookieSecure(ctx)) c.MustSet(ctx, KeyCookieSecure, false) assert.False(t, c.CookieSecure(ctx)) c.MustSet(ctx, KeyDevelopmentMode, false) assert.True(t, c.CookieSecure(ctx)) } func TestTokenRefreshHookURL(t *testing.T) { ctx := context.Background() l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) c := MustNew(context.Background(), l, configx.SkipValidation()) assert.EqualValues(t, (*url.URL)(nil), c.TokenRefreshHookURL(ctx)) c.MustSet(ctx, KeyRefreshTokenHookURL, "") assert.EqualValues(t, (*url.URL)(nil), c.TokenRefreshHookURL(ctx)) c.MustSet(ctx, KeyRefreshTokenHookURL, "http://localhost:8080/oauth/token_refresh") assert.EqualValues(t, "http://localhost:8080/oauth/token_refresh", c.TokenRefreshHookURL(ctx).String()) } func TestJWTBearer(t *testing.T) { l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) ctx := context.Background() // p.MustSet(ctx, KeyOAuth2GrantJWTClientAuthOptional, false) p.MustSet(ctx, KeyOAuth2GrantJWTMaxDuration, "1h") p.MustSet(ctx, KeyOAuth2GrantJWTIssuedDateOptional, false) p.MustSet(ctx, KeyOAuth2GrantJWTIDOptional, false) // assert.Equal(t, false, p.GetGrantTypeJWTBearerCanSkipClientAuth(ctx)) assert.Equal(t, 1.0, p.GetJWTMaxDuration(ctx).Hours()) assert.Equal(t, false, p.GetGrantTypeJWTBearerIssuedDateOptional(ctx)) assert.Equal(t, false, p.GetGrantTypeJWTBearerIDOptional(ctx)) p2 := MustNew(context.Background(), l) // p2.MustSet(ctx, KeyOAuth2GrantJWTClientAuthOptional, true) p2.MustSet(ctx, KeyOAuth2GrantJWTMaxDuration, "24h") p2.MustSet(ctx, KeyOAuth2GrantJWTIssuedDateOptional, true) p2.MustSet(ctx, KeyOAuth2GrantJWTIDOptional, true) // assert.Equal(t, true, p2.GetGrantTypeJWTBearerCanSkipClientAuth(ctx)) assert.Equal(t, 24.0, p2.GetJWTMaxDuration(ctx).Hours()) assert.Equal(t, true, p2.GetGrantTypeJWTBearerIssuedDateOptional(ctx)) assert.Equal(t, true, p2.GetGrantTypeJWTBearerIDOptional(ctx)) } func TestJWTScopeClaimStrategy(t *testing.T) { l := logrusx.New("", "") l.Logrus().SetOutput(io.Discard) p := MustNew(context.Background(), l) ctx := context.Background() assert.Equal(t, jwt.JWTScopeFieldList, p.GetJWTScopeField(ctx)) p.MustSet(ctx, KeyJWTScopeClaimStrategy, "list") assert.Equal(t, jwt.JWTScopeFieldList, p.GetJWTScopeField(ctx)) p.MustSet(ctx, KeyJWTScopeClaimStrategy, "string") assert.Equal(t, jwt.JWTScopeFieldString, p.GetJWTScopeField(ctx)) p.MustSet(ctx, KeyJWTScopeClaimStrategy, "both") assert.Equal(t, jwt.JWTScopeFieldBoth, p.GetJWTScopeField(ctx)) }
Go
hydra/driver/config/serve.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "context" "fmt" "os" "strings" "github.com/ory/x/contextx" "github.com/rs/cors" "github.com/ory/x/configx" ) const ( KeySuffixListenOnHost = "host" KeySuffixListenOnPort = "port" KeySuffixSocketOwner = "socket.owner" KeySuffixSocketGroup = "socket.group" KeySuffixSocketMode = "socket.mode" KeySuffixDisableHealthAccessLog = "request_log.disable_for_health" ) var ( PublicInterface ServeInterface = &servePrefix{ prefix: "serve.public", } AdminInterface ServeInterface = &servePrefix{ prefix: "serve.admin", } ) type ServeInterface interface { Key(suffix string) string String() string } type servePrefix struct { prefix string } func (iface *servePrefix) Key(suffix string) string { if suffix == KeyRoot { return iface.prefix } return fmt.Sprintf("%s.%s", iface.prefix, suffix) } func (iface *servePrefix) String() string { return iface.prefix } func (p *DefaultProvider) ListenOn(iface ServeInterface) string { host, port := p.host(iface), p.port(iface) if strings.HasPrefix(host, "unix:") { return host } return fmt.Sprintf("%s:%d", host, port) } func (p *DefaultProvider) SocketPermission(iface ServeInterface) *configx.UnixPermission { return &configx.UnixPermission{ Owner: p.getProvider(contextx.RootContext).String(iface.Key(KeySuffixSocketOwner)), Group: p.getProvider(contextx.RootContext).String(iface.Key(KeySuffixSocketGroup)), Mode: os.FileMode(p.getProvider(contextx.RootContext).IntF(iface.Key(KeySuffixSocketMode), 0755)), } } func (p *DefaultProvider) CORS(ctx context.Context, iface ServeInterface) (cors.Options, bool) { return p.getProvider(ctx).CORS(iface.Key(KeyRoot), cors.Options{ AllowedMethods: []string{ "POST", "GET", "PUT", "PATCH", "DELETE", "CONNECT", "HEAD", "OPTIONS", "TRACE", }, AllowedHeaders: []string{ "Accept", "Content-Type", "Content-Length", "Accept-Language", "Content-Language", "Authorization", }, ExposedHeaders: []string{ "Cache-Control", "Expires", "Last-Modified", "Pragma", "Content-Length", "Content-Language", "Content-Type", }, AllowCredentials: true, }) } func (p *DefaultProvider) DisableHealthAccessLog(iface ServeInterface) bool { return p.getProvider(contextx.RootContext).Bool(iface.Key(KeySuffixDisableHealthAccessLog)) } func (p *DefaultProvider) host(iface ServeInterface) string { return p.getProvider(contextx.RootContext).String(iface.Key(KeySuffixListenOnHost)) } func (p *DefaultProvider) port(iface ServeInterface) int { return p.getProvider(contextx.RootContext).Int(iface.Key(KeySuffixListenOnPort)) }
Go
hydra/driver/config/tls.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "context" "crypto/tls" "github.com/pkg/errors" "github.com/ory/x/logrusx" "github.com/ory/x/tlsx" ) const ( KeySuffixTLSEnabled = "tls.enabled" KeySuffixTLSAllowTerminationFrom = "tls.allow_termination_from" KeySuffixTLSCertString = "tls.cert.base64" KeySuffixTLSKeyString = "tls.key.base64" KeySuffixTLSCertPath = "tls.cert.path" KeySuffixTLSKeyPath = "tls.key.path" KeyTLSAllowTerminationFrom = "serve." + KeySuffixTLSAllowTerminationFrom KeyTLSCertString = "serve." + KeySuffixTLSCertString KeyTLSKeyString = "serve." + KeySuffixTLSKeyString KeyTLSCertPath = "serve." + KeySuffixTLSCertPath KeyTLSKeyPath = "serve." + KeySuffixTLSKeyPath KeyTLSEnabled = "serve." + KeySuffixTLSEnabled ) type TLSConfig interface { Enabled() bool AllowTerminationFrom() []string GetCertificateFunc(stopReload <-chan struct{}, _ *logrusx.Logger) (func(*tls.ClientHelloInfo) (*tls.Certificate, error), error) } var _ TLSConfig = (*tlsConfig)(nil) type tlsConfig struct { enabled bool allowTerminationFrom []string certString string keyString string certPath string keyPath string } func (c *tlsConfig) Enabled() bool { return c.enabled } func (c *tlsConfig) AllowTerminationFrom() []string { return c.allowTerminationFrom } func (p *DefaultProvider) TLS(ctx context.Context, iface ServeInterface) TLSConfig { return &tlsConfig{ enabled: p.getProvider(ctx).BoolF(iface.Key(KeySuffixTLSEnabled), p.getProvider(ctx).Bool(KeyTLSEnabled)), allowTerminationFrom: p.getProvider(ctx).StringsF(iface.Key(KeySuffixTLSAllowTerminationFrom), p.getProvider(ctx).Strings(KeyTLSAllowTerminationFrom)), certString: p.getProvider(ctx).StringF(iface.Key(KeySuffixTLSCertString), p.getProvider(ctx).String(KeyTLSCertString)), keyString: p.getProvider(ctx).StringF(iface.Key(KeySuffixTLSKeyString), p.getProvider(ctx).String(KeyTLSKeyString)), certPath: p.getProvider(ctx).StringF(iface.Key(KeySuffixTLSCertPath), p.getProvider(ctx).String(KeyTLSCertPath)), keyPath: p.getProvider(ctx).StringF(iface.Key(KeySuffixTLSKeyPath), p.getProvider(ctx).String(KeyTLSKeyPath)), } } func (c *tlsConfig) GetCertificateFunc(stopReload <-chan struct{}, log *logrusx.Logger) (func(*tls.ClientHelloInfo) (*tls.Certificate, error), error) { if c.certPath != "" && c.keyPath != "" { // attempt to load from disk first (enables hot-reloading) ctx, cancel := context.WithCancel(context.Background()) go func() { <-stopReload cancel() }() errs := make(chan error, 1) getCert, err := tlsx.GetCertificate(ctx, c.certPath, c.keyPath, errs) if err != nil { return nil, errors.WithStack(err) } go func() { for err := range errs { log.WithError(err).Error("Failed to reload TLS certificates. Using the previously loaded certificates.") } }() return getCert, nil } if c.certString != "" && c.keyString != "" { // base64-encoded directly in config cert, err := tlsx.CertificateFromBase64(c.certString, c.keyString) if err != nil { return nil, errors.WithStack(err) } return func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &cert, nil }, nil } return nil, tlsx.ErrNoCertificatesConfigured }
Go
hydra/driver/config/types.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "strings" "github.com/ory/x/stringsx" ) // AccessTokenStrategyType is the type of access token strategy. type AccessTokenStrategyType string const ( // AccessTokenJWTStrategy is the JWT access token strategy. AccessTokenJWTStrategy AccessTokenStrategyType = "jwt" // AccessTokenDefaultStrategy is the default access token strategy using HMAC-SHA pass-by-reference tokens. AccessTokenDefaultStrategy AccessTokenStrategyType = "opaque" ) // ToAccessTokenStrategyType converts a string to an AccessTokenStrategyType func ToAccessTokenStrategyType(strategy string) (AccessTokenStrategyType, error) { switch f := stringsx.SwitchExact(strings.ToLower(strategy)); { case f.AddCase("jwt"): return AccessTokenJWTStrategy, nil case f.AddCase("opaque"): return AccessTokenDefaultStrategy, nil default: return "", f.ToUnknownCaseErr() } }
Go
hydra/driver/config/types_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package config import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestToAccessTokenStrategyType(t *testing.T) { actual, err := ToAccessTokenStrategyType("opaque") require.NoError(t, err) assert.Equal(t, AccessTokenDefaultStrategy, actual) actual, err = ToAccessTokenStrategyType("jwt") require.NoError(t, err) assert.Equal(t, AccessTokenJWTStrategy, actual) _, err = ToAccessTokenStrategyType("invalid") require.Error(t, err) }