language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=DELETE-without_incorrect_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=DELETE-with_a_different_client_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=GET-without_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=GET-without_incorrect_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=GET-with_a_different_client_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=PUT-without_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=PUT-without_incorrect_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-case=selfservice_with_incorrect_or_missing_auth-endpoint=selfservice-method=PUT-with_a_different_client_auth.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=0-description=basic_dynamic_client_registration.json
{ "client_name": "", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=1-description=basic_admin_registration.json
{ "client_name": "", "client_secret": "averylongsecret", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": { "foo": "bar" }, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=1-description=basic_dynamic_client_registration.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is not allowed to choose your own OAuth2 Client secret." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=10-description=empty_ID_succeeds.json
{ "client_name": "", "client_secret": "averylongsecret", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=2-description=empty_ID_succeeds.json
{ "client_name": "", "client_secret": "averylongsecret", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=2-description=metadata_fails_for_dynamic_client_registration.json
{ "error": "invalid_client_metadata", "error_description": "The value of one of the Client Metadata fields is invalid and the server has rejected this request. Note that an Authorization Server MAY choose to substitute a valid value for any requested parameter of a Client's Metadata. 'metadata' cannot be set for dynamic client registration" }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=3-description=short_secret_fails_for_admin.json
{ "error": "invalid_client_metadata", "error_description": "The value of one of the Client Metadata fields is invalid and the server has rejected this request. Note that an Authorization Server MAY choose to substitute a valid value for any requested parameter of a Client's Metadata. Field client_secret must contain a secret that is at least 6 characters long." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=4-description=non-uuid_fails.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is no longer possible to set an OAuth2 Client ID as a user. The system will generate a unique ID for you." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=5-description=setting_client_id_fails.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is no longer possible to set an OAuth2 Client ID as a user. The system will generate a unique ID for you." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=6-description=setting_access_token_strategy_fails.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is not allowed to choose your own access token strategy." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=6-description=setting_skip_consent_fails_for_dynamic_registration.json
{ "error": "invalid_request", "error_description": "'skip_consent' cannot be set for dynamic client registration" }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=7-description=basic_dynamic_client_registration.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is not allowed to choose your own OAuth2 Client secret." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=7-description=setting_skip_consent_fails_for_dynamic_registration.json
{ "error": "invalid_request", "error_description": "'skip_consent' cannot be set for dynamic client registration" }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=7-description=setting_skip_consent_suceeds_for_admin_registration.json
{ "client_name": "", "client_secret": "2SKZkBf2P5g4toAXXnCrr~_sDM", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": true, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=8-description=basic_dynamic_client_registration.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is not allowed to choose your own OAuth2 Client secret." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=8-description=empty_ID_succeeds.json
{ "client_name": "", "client_secret": "averylongsecret", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=8-description=setting_skip_consent_suceeds_for_admin_registration.json
{ "client_name": "", "client_secret": "2SKZkBf2P5g4toAXXnCrr~_sDM", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": true, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=9-description=basic_dynamic_client_registration.json
{ "error": "The request was malformed or contained invalid parameters", "error_description": "It is not allowed to choose your own OAuth2 Client secret." }
JSON
hydra/client/.snapshots/TestHandler-common-case=create_clients-case=9-description=empty_ID_succeeds.json
{ "client_name": "", "client_secret": "averylongsecret", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-common-case=creating_a_client_dynamically_does_not_allow_setting_the_secret.json
{ "body": { "error": "The request was malformed or contained invalid parameters", "error_description": "It is not allowed to choose your own OAuth2 Client secret." }, "status": 400 }
JSON
hydra/client/.snapshots/TestHandler-common-case=delete_non-existing_client-path=-clients-foo.json
{ "body": { "error": "Unable to locate the resource", "error_description": "" }, "status": 404 }
JSON
hydra/client/.snapshots/TestHandler-common-case=delete_non-existing_client-path=-oauth2-register-foo.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-common-case=fetching_existing_client-endpoint=admin.json
{ "body": { "client_name": "", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": [], "response_types": [], "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": [], "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }, "status": 200 }
JSON
hydra/client/.snapshots/TestHandler-common-case=fetching_existing_client-endpoint=selfservice.json
{ "body": { "client_name": "", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": [], "response_types": [], "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": [], "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }, "status": 200 }
JSON
hydra/client/.snapshots/TestHandler-common-case=fetching_non-existing_client-path=-clients-foo.json
{ "body": { "error": "Unable to locate the resource", "error_description": "" }, "status": 404 }
JSON
hydra/client/.snapshots/TestHandler-common-case=fetching_non-existing_client-path=-oauth2-register-foo.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-common-case=patching_non-existing_client.json
{ "body": { "error": "Unable to locate the resource", "error_description": "" }, "status": 404 }
JSON
hydra/client/.snapshots/TestHandler-common-case=update_the_lifespans_of_an_OAuth2_client.json
{ "body": { "client_name": "update-existing-client-lifespans", "redirect_uris": [ "http://localhost:3000/cb" ], "grant_types": [], "response_types": [], "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": [], "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": "31h0m0s", "authorization_code_grant_id_token_lifespan": "32h0m0s", "authorization_code_grant_refresh_token_lifespan": "33h0m0s", "client_credentials_grant_access_token_lifespan": "34h0m0s", "implicit_grant_access_token_lifespan": "35h0m0s", "implicit_grant_id_token_lifespan": "36h0m0s", "jwt_bearer_grant_access_token_lifespan": "37h0m0s", "refresh_token_grant_id_token_lifespan": "40h0m0s", "refresh_token_grant_access_token_lifespan": "41h0m0s", "refresh_token_grant_refresh_token_lifespan": "42h0m0s" }, "status": 200 }
JSON
hydra/client/.snapshots/TestHandler-common-case=updating_existing_client-endpoint=admin.json
{ "body": { "client_name": "", "client_secret": "averylongsecret", "redirect_uris": [ "http://localhost:3000/cb", "https://foobar.com" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }, "status": 200 }
JSON
hydra/client/.snapshots/TestHandler-common-case=updating_existing_client-endpoint=dynamic_client_registration.json
{ "body": { "client_name": "", "redirect_uris": [ "http://localhost:3000/cb", "https://foobar.com" ], "grant_types": null, "response_types": null, "scope": "offline_access offline openid", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "public", "jwks": {}, "token_endpoint_auth_method": "client_secret_basic", "userinfo_signed_response_alg": "none", "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }, "status": 200 }
JSON
hydra/client/.snapshots/TestHandler-common-case=updating_existing_client-endpoint=dynamic_client_registration_does_not_allow_changing_the_secret.json
{ "body": { "error": "The requested action was forbidden", "error_description": "It is not allowed to choose your own OAuth2 Client secret." }, "status": 403 }
JSON
hydra/client/.snapshots/TestHandler-common-case=updating_existing_client_fails_with_metadata_on_self_service.json
{ "body": { "error": "invalid_client_metadata", "error_description": "The value of one of the Client Metadata fields is invalid and the server has rejected this request. Note that an Authorization Server MAY choose to substitute a valid value for any requested parameter of a Client's Metadata. 'metadata' cannot be set for dynamic client registration" }, "status": 400 }
JSON
hydra/client/.snapshots/TestHandler-common-case=updating_non-existing_client-path=-clients-foo.json
{ "body": { "error": "Unable to locate the resource", "error_description": "" }, "status": 404 }
JSON
hydra/client/.snapshots/TestHandler-common-case=updating_non-existing_client-path=-oauth2-register-foo.json
{ "body": { "error": "The request could not be authorized", "error_description": "The requested OAuth 2.0 client does not exist or you provided incorrect credentials." }, "status": 401 }
JSON
hydra/client/.snapshots/TestHandler-create_client_registration_tokens-case=0-dynamic=true.json
{ "client_name": "", "redirect_uris": null, "grant_types": null, "response_types": null, "scope": "", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "", "jwks": {}, "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-create_client_registration_tokens-case=1-dynamic=false.json
{ "client_name": "", "redirect_uris": null, "grant_types": null, "response_types": null, "scope": "", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "", "jwks": {}, "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
JSON
hydra/client/.snapshots/TestHandler-create_client_registration_tokens-case=2-dynamic=false.json
{ "client_name": "", "client_secret": "01bbf13a-ae3e-44d5-b4b4-dd78137041be", "redirect_uris": null, "grant_types": null, "response_types": null, "scope": "", "audience": [], "owner": "", "policy_uri": "", "allowed_cors_origins": [], "tos_uri": "", "client_uri": "", "logo_uri": "", "contacts": null, "client_secret_expires_at": 0, "subject_type": "", "jwks": {}, "metadata": {}, "skip_consent": false, "authorization_code_grant_access_token_lifespan": null, "authorization_code_grant_id_token_lifespan": null, "authorization_code_grant_refresh_token_lifespan": null, "client_credentials_grant_access_token_lifespan": null, "implicit_grant_access_token_lifespan": null, "implicit_grant_id_token_lifespan": null, "jwt_bearer_grant_access_token_lifespan": null, "refresh_token_grant_id_token_lifespan": null, "refresh_token_grant_access_token_lifespan": null, "refresh_token_grant_refresh_token_lifespan": null }
Go
hydra/cmd/cmd_create_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/ory/x/pointerx" "github.com/ory/hydra/v2/cmd/cli" ) const ( flagClientAllowedCORSOrigin = "allowed-cors-origin" flagClientAudience = "audience" flagClientBackchannelLogoutCallback = "backchannel-logout-callback" flagClientName = "name" flagClientClientURI = "client-uri" flagClientContact = "contact" flagClientFrontChannelLogoutSessionRequired = "frontchannel-logout-session-required" flagClientFrontChannelLogoutCallback = "frontchannel-logout-callback" flagClientGrantType = "grant-type" flagClientJWKSURI = "jwks-uri" flagClientLogoURI = "logo-uri" flagClientMetadata = "metadata" flagClientOwner = "owner" flagClientPolicyURI = "policy-uri" flagClientPostLogoutCallback = "post-logout-callback" flagClientRedirectURI = "redirect-uri" flagClientRequestObjectSigningAlg = "request-object-signing-alg" flagClientRequestURI = "request-uri" flagClientResponseType = "response-type" flagClientScope = "scope" flagClientSectorIdentifierURI = "sector-identifier-uri" flagClientSkipConsent = "skip-consent" flagClientSubjectType = "subject-type" flagClientTokenEndpointAuthMethod = "token-endpoint-auth-method" flagClientSecret = "secret" flagClientTOSURI = "tos-uri" flagClientBackChannelLogoutSessionRequired = "backchannel-logout-session-required" ) func NewCreateClientsCommand() *cobra.Command { cmd := &cobra.Command{ Use: "oauth2-client", Short: "Create an OAuth 2.0 Client", Aliases: []string{"client"}, Args: cobra.NoArgs, Example: `{{ .CommandPath }} -n "my app" -c http://localhost/cb -g authorization_code -r code -a core,foobar Use the tool jq (or any other JSON tool) to get the OAuth2 Client ID and and Secret: client=$({{ .CommandPath }} \ --format json \ ...) echo $client # Parse the JSON response using jq to get the client ID and client secret: client_id=$(echo $client | jq -r '.client_id') client_secret=$(echo $client | jq -r '.client_secret')`, Long: `This command creates an OAuth 2.0 Client which can be used to perform various OAuth 2.0 Flows like the Authorize Code, Implicit, Refresh flow. This command allows settings all fields defined in the OpenID Connect Dynamic Client Registration standard. To encrypt an auto-generated OAuth2 Client Secret, use flags ` + "`--pgp-key`" + `, ` + "`--pgp-key-url`" + ` or ` + "`--keybase`" + ` flag, for example: {{ .CommandPath }} -n "my app" -g client_credentials -r token -a core,foobar --keybase keybase_username `, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } ek, encryptSecret, err := cli.NewEncryptionKey(cmd, nil) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Failed to load encryption key: %s", err) return err } secret := flagx.MustGetString(cmd, flagClientSecret) //nolint:bodyclose client, _, err := m.OAuth2Api.CreateOAuth2Client(cmd.Context()).OAuth2Client(clientFromFlags(cmd)).Execute() if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } if client.ClientSecret == nil && len(secret) > 0 { client.ClientSecret = pointerx.String(secret) } if encryptSecret && client.ClientSecret != nil { enc, err := ek.Encrypt([]byte(*client.ClientSecret)) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Failed to encrypt client secret: %s", err) return cmdx.FailSilently(cmd) } client.ClientSecret = pointerx.String(enc.Base64Encode()) } cmdx.PrintRow(cmd, (*outputOAuth2Client)(client)) return nil }, } registerClientFlags(cmd.Flags()) return cmd }
Go
hydra/cmd/cmd_create_client_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" "github.com/ory/x/snapshotx" ) func TestCreateClient(t *testing.T) { ctx := context.Background() c := cmd.NewCreateClientsCommand() reg := setup(t, c) t.Run("case=creates successfully", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c)) assert.NotEmpty(t, actual.Get("client_id").String()) assert.NotEmpty(t, actual.Get("client_secret").String()) expected, err := reg.ClientManager().GetClient(ctx, actual.Get("client_id").String()) require.NoError(t, err) assert.Equal(t, expected.GetID(), actual.Get("client_id").String()) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) t.Run("case=supports setting flags", func(t *testing.T) { useSecret := "some-userset-secret" actual := gjson.Parse(cmdx.ExecNoErr(t, c, "--secret", useSecret, "--metadata", `{"foo":"bar"}`, "--audience", "https://www.ory.sh/audience1", "--audience", "https://www.ory.sh/audience2", )) assert.NotEmpty(t, actual.Get("client_id").String()) assert.Equal(t, useSecret, actual.Get("client_secret").String()) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) t.Run("case=supports encryption", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, "--secret", "some-userset-secret", "--pgp-key", base64EncodedPGPPublicKey(t), )) assert.NotEmpty(t, actual.Get("client_id").String()) assert.NotEmpty(t, actual.Get("client_secret").String()) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) }
Go
hydra/cmd/cmd_create_jwks.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "context" "github.com/spf13/cobra" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" ) func NewCreateJWKSCmd() *cobra.Command { const alg = "alg" const use = "use" cmd := &cobra.Command{ Use: "jwk <set-id> [<key-id>]", Aliases: []string{"jwks"}, Args: cobra.RangeArgs(1, 2), Example: `{{ .CommandPath }} <my-jwk-set> --alg RS256 --use sig`, Short: "Create a JSON Web Key Set with a JSON Web Key", RunE: func(cmd *cobra.Command, args []string) error { cmd.CommandPath() m, _, err := cliclient.NewClient(cmd) if err != nil { return err } var kid string if len(args) == 2 { kid = args[1] } //nolint:bodyclose jwks, _, err := m.JwkApi.CreateJsonWebKeySet(context.Background(), args[0]).CreateJsonWebKeySet(hydra.CreateJsonWebKeySet{ Alg: flagx.MustGetString(cmd, alg), Kid: kid, Use: flagx.MustGetString(cmd, use), }).Execute() if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } cmdx.PrintTable(cmd, &outputJSONWebKeyCollection{Keys: jwks.Keys, Set: args[0]}) return nil }, } cmd.Root().Name() cmd.Flags().String(alg, "RS256", "The algorithm to be used to generated they key. Supports: RS256, RS512, ES256, ES512, EdDSA") cmd.Flags().String(use, "sig", "The intended use of this key. Supports: sig, enc") return cmd }
Go
hydra/cmd/cmd_create_jwks_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "testing" "github.com/gofrs/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) func TestCreateJWKS(t *testing.T) { ctx := context.Background() c := cmd.NewCreateJWKSCmd() reg := setup(t, c) t.Run("case=creates successfully", func(t *testing.T) { set := uuid.Must(uuid.NewV4()).String() actual := gjson.Parse(cmdx.ExecNoErr(t, c, set, "--use", "enc", "--alg", "ES256")) assert.Len(t, actual.Get("keys.0").Array(), 1, "%s", actual.Raw) assert.NotEmpty(t, actual.Get("keys.0.kid").Array(), "%s", actual.Raw) assert.Equal(t, "ES256", actual.Get("keys.0.alg").String(), "%s", actual.Raw) expected, err := reg.KeyManager().GetKeySet(ctx, set) require.NoError(t, err) assert.Equal(t, expected.Keys[0].KeyID, actual.Get("keys.0.kid").String()) }) }
Go
hydra/cmd/cmd_delete.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewDeleteCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "delete", Short: "Delete resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_delete_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" ) func NewDeleteClientCmd() *cobra.Command { return &cobra.Command{ Use: "oauth2-client <id-1> [<id-2> ...]", Aliases: []string{"client", "clients", "oauth2-clients"}, Args: cobra.MinimumNArgs(1), Short: "Delete one or more OAuth 2.0 Clients by their ID(s)", Long: "This command deletes one or more OAuth 2.0 Clients by their respective IDs.", Example: `{{ .CommandPath }} <client-1> <client-2> <client-3> To delete OAuth 2.0 Clients with the owner of "[email protected]", run: {{ .CommandPath }} $({{ .Root.Name }} list oauth2-clients --format json | jq -r 'map(select(.contacts[] == "[email protected]")) | .[].client_id')`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } var ( deleted = make([]cmdx.OutputIder, 0, len(args)) failed = make(map[string]error) ) for _, c := range args { _, err := m.OAuth2Api.DeleteOAuth2Client(cmd.Context(), c).Execute() //nolint:bodyclose if err != nil { failed[c] = cmdx.PrintOpenAPIError(cmd, err) continue } deleted = append(deleted, cmdx.OutputIder(c)) } if len(deleted) == 1 { cmdx.PrintRow(cmd, &deleted[0]) } else if len(deleted) > 1 { cmdx.PrintTable(cmd, &cmdx.OutputIderCollection{Items: deleted}) } cmdx.PrintErrors(cmd, failed) if len(failed) != 0 { return cmdx.FailSilently(cmd) } return nil }, } }
Go
hydra/cmd/cmd_delete_client_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "encoding/json" "fmt" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/assertx" "github.com/ory/x/cmdx" "github.com/ory/x/snapshotx" "github.com/ory/x/sqlcon" ) func TestDeleteClient(t *testing.T) { ctx := context.Background() c := cmd.NewDeleteClientCmd() reg := setup(t, c) t.Run("case=deletes client", func(t *testing.T) { expected := createClient(t, reg, nil) stdout := cmdx.ExecNoErr(t, c, expected.GetID()) assert.Equal(t, fmt.Sprintf(`"%s"`, expected.GetID()), strings.TrimSpace(stdout)) _, err := reg.ClientManager().GetClient(ctx, expected.GetID()) assert.ErrorIs(t, err, sqlcon.ErrNoRows) }) t.Run("case=deletes multiple clients", func(t *testing.T) { expected1 := createClient(t, reg, nil) expected2 := createClient(t, reg, nil) assertx.EqualAsJSON(t, []string{expected1.GetID(), expected2.GetID()}, json.RawMessage(cmdx.ExecNoErr(t, c, expected1.GetID(), expected2.GetID()))) _, err := reg.ClientManager().GetClient(ctx, expected1.GetID()) assert.ErrorIs(t, err, sqlcon.ErrNoRows) _, err = reg.ClientManager().GetClient(ctx, expected2.GetID()) assert.ErrorIs(t, err, sqlcon.ErrNoRows) }) t.Run("case=one client deletion fails", func(t *testing.T) { expected := createClient(t, reg, nil) stdout, stderr, err := cmdx.Exec(t, c, nil, "i-do-not-exist", expected.GetID()) require.Error(t, err) assert.Equal(t, fmt.Sprintf(`"%s"`, expected.GetID()), strings.TrimSpace(stdout)) snapshotx.SnapshotT(t, stderr) _, err = reg.ClientManager().GetClient(ctx, expected.GetID()) assert.ErrorIs(t, err, sqlcon.ErrNoRows) }) }
Go
hydra/cmd/cmd_delete_jwks.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "context" "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" ) func NewDeleteJWKSCommand() *cobra.Command { return &cobra.Command{ Use: "jwk <id-1> [<id-2> ...]", Aliases: []string{"jwks"}, Args: cobra.MinimumNArgs(1), Short: "Delete one or more JSON Web Key Sets by their set ID", Long: "This command deletes one or more JSON Web Key Sets by their respective set IDs.", Example: `{{ .CommandPath }} <set-1> <set-2> <set-3>`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } var ( deleted = make([]cmdx.OutputIder, 0, len(args)) failed = make(map[string]error) ) for _, c := range args { _, err = m.JwkApi.DeleteJsonWebKeySet(context.Background(), c).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } deleted = append(deleted, cmdx.OutputIder(c)) } if len(deleted) == 1 { cmdx.PrintRow(cmd, &deleted[0]) } else if len(deleted) > 1 { cmdx.PrintTable(cmd, &cmdx.OutputIderCollection{Items: deleted}) } cmdx.PrintErrors(cmd, failed) if len(failed) != 0 { return cmdx.FailSilently(cmd) } return nil }, } }
Go
hydra/cmd/cmd_delete_jwks_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "encoding/json" "fmt" "strings" "testing" "github.com/gofrs/uuid" "github.com/ory/hydra/v2/x" "github.com/stretchr/testify/assert" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/assertx" "github.com/ory/x/cmdx" ) func TestDeleteJwks(t *testing.T) { ctx := context.Background() c := cmd.NewDeleteJWKSCommand() reg := setup(t, c) t.Run("case=deletes jwks", func(t *testing.T) { set := uuid.Must(uuid.NewV4()).String() _ = createJWK(t, reg, set, "RS256") stdout := cmdx.ExecNoErr(t, c, set) assert.Equal(t, fmt.Sprintf(`"%s"`, set), strings.TrimSpace(stdout)) _, err := reg.KeyManager().GetKeySet(ctx, set) assert.ErrorIs(t, err, x.ErrNotFound) }) t.Run("case=deletes multiple jwkss", func(t *testing.T) { set1 := uuid.Must(uuid.NewV4()).String() set2 := uuid.Must(uuid.NewV4()).String() _ = createJWK(t, reg, set1, "RS256") _ = createJWK(t, reg, set2, "RS256") assertx.EqualAsJSON(t, []string{set1, set2}, json.RawMessage(cmdx.ExecNoErr(t, c, set1, set2))) _, err := reg.KeyManager().GetKeySet(ctx, set1) assert.ErrorIs(t, err, x.ErrNotFound) _, err = reg.KeyManager().GetKeySet(ctx, set2) assert.ErrorIs(t, err, x.ErrNotFound) }) }
Go
hydra/cmd/cmd_delete_tokens.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" ) func NewDeleteAccessTokensCmd() *cobra.Command { cmd := &cobra.Command{ Use: "access-tokens <client-id>", Args: cobra.ExactArgs(1), Example: `{{ .CommandPath }} <client-id>`, Short: "Delete all OAuth2 Access Tokens of an OAuth2 Client", RunE: func(cmd *cobra.Command, args []string) error { client, _, err := cliclient.NewClient(cmd) if err != nil { return err } clientID := args[0] _, err = client.OAuth2Api.DeleteOAuth2Token(cmd.Context()).ClientId(clientID).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } cmdx.PrintRow(cmd, cmdx.OutputIder(clientID)) return nil }, } return cmd }
Go
hydra/cmd/cmd_delete_tokens_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "fmt" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) func TestDeleteAccessTokensCmd(t *testing.T) { c := cmd.NewDeleteAccessTokensCmd() reg := setup(t, c) expected := createClientCredentialsClient(t, reg) t.Run("case=deletes tokens", func(t *testing.T) { stdout := cmdx.ExecNoErr(t, c, expected.GetID()) assert.Equal(t, fmt.Sprintf(`"%s"`, expected.GetID()), strings.TrimSpace(stdout)) }) }
Go
hydra/cmd/cmd_get.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewGetCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "get", Short: "Get resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_get_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" ) func NewGetClientsCmd() *cobra.Command { return &cobra.Command{ Use: "oauth2-client <id-1> [<id-2> ...]", Aliases: []string{"client", "clients", "oauth2-clients"}, Args: cobra.MinimumNArgs(1), Short: "Get one or more OAuth 2.0 Clients by their ID(s)", Long: `This command gets all the details about an OAuth 2.0 Client. You can use this command in combination with jq.`, Example: `To get the OAuth 2.0 Client's secret, run: {{ .CommandPath }} <your-client-id> --format json | jq -r '.client_secret'`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } clients := make([]hydra.OAuth2Client, 0, len(args)) for _, id := range args { client, _, err := m.OAuth2Api.GetOAuth2Client(cmd.Context(), id).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } clients = append(clients, *client) } if len(clients) == 1 { cmdx.PrintRow(cmd, (*outputOAuth2Client)(&clients[0])) } else if len(clients) > 1 { cmdx.PrintTable(cmd, &outputOAuth2ClientCollection{clients}) } return nil }, } }
Go
hydra/cmd/cmd_get_client_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" "github.com/ory/x/snapshotx" ) func TestGetClient(t *testing.T) { ctx := context.Background() c := cmd.NewGetClientsCmd() reg := setup(t, c) expected := createClient(t, reg, nil) t.Run("case=gets client", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, expected.ID.String())) assert.NotEmpty(t, actual.Get("client_id").String()) assert.Empty(t, actual.Get("client_secret").String()) expected, err := reg.ClientManager().GetClient(ctx, actual.Get("client_id").String()) require.NoError(t, err) assert.Equal(t, expected.GetID(), actual.Get("client_id").String()) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) t.Run("case=gets multiple clients", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, expected.ID.String(), expected.ID.String())) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) }
Go
hydra/cmd/cmd_get_jwks.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" ) func NewGetJWKSCmd() *cobra.Command { return &cobra.Command{ Use: "jwk set-1 [set-2] ...", Aliases: []string{"jwks"}, Args: cobra.MinimumNArgs(1), Short: "Get one or more JSON Web Key Set by its ID(s)", Long: `This command gets all the details about an JSON Web Key. You can use this command in combination with jq.`, Example: `To get the JSON Web Key Set's secret, run: {{ .CommandPath }} <set-id> | jq -r '.[].use'`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } var sets outputJSONWebKeyCollection for _, set := range args { key, _, err := m.JwkApi.GetJsonWebKeySet(cmd.Context(), set).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } sets.Keys = append(sets.Keys, key.Keys...) } if len(sets.Keys) == 1 { cmdx.PrintRow(cmd, outputJsonWebKey{Set: args[0], JsonWebKey: sets.Keys[0]}) } else if len(sets.Keys) > 1 { cmdx.PrintTable(cmd, sets) } return nil }, } }
Go
hydra/cmd/cmd_get_jwks_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "testing" "github.com/gofrs/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) func TestGetJwks(t *testing.T) { ctx := context.Background() c := cmd.NewGetJWKSCmd() reg := setup(t, c) set := uuid.Must(uuid.NewV4()).String() _ = createJWK(t, reg, set, "RS256") t.Run("case=gets jwks", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, set)) assert.NotEmpty(t, actual.Get("kid").String(), actual.Raw) expected, err := reg.KeyManager().GetKeySet(ctx, set) require.NoError(t, err) assert.Equal(t, expected.Keys[0].KeyID, actual.Get("kid").String()) }) }
Go
hydra/cmd/cmd_helper_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "encoding/json" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/x/flagx" "github.com/ory/x/pointerx" ) func clientFromFlags(cmd *cobra.Command) hydra.OAuth2Client { return hydra.OAuth2Client{ AllowedCorsOrigins: flagx.MustGetStringSlice(cmd, flagClientAllowedCORSOrigin), Audience: flagx.MustGetStringSlice(cmd, flagClientAudience), BackchannelLogoutSessionRequired: pointerx.Bool(flagx.MustGetBool(cmd, flagClientBackChannelLogoutSessionRequired)), BackchannelLogoutUri: pointerx.String(flagx.MustGetString(cmd, flagClientBackchannelLogoutCallback)), ClientName: pointerx.String(flagx.MustGetString(cmd, flagClientName)), ClientSecret: pointerx.String(flagx.MustGetString(cmd, flagClientSecret)), ClientUri: pointerx.String(flagx.MustGetString(cmd, flagClientClientURI)), Contacts: flagx.MustGetStringSlice(cmd, flagClientContact), FrontchannelLogoutSessionRequired: pointerx.Bool(flagx.MustGetBool(cmd, flagClientFrontChannelLogoutSessionRequired)), FrontchannelLogoutUri: pointerx.String(flagx.MustGetString(cmd, flagClientFrontChannelLogoutCallback)), GrantTypes: flagx.MustGetStringSlice(cmd, flagClientGrantType), JwksUri: pointerx.String(flagx.MustGetString(cmd, flagClientJWKSURI)), LogoUri: pointerx.String(flagx.MustGetString(cmd, flagClientLogoURI)), Metadata: json.RawMessage(flagx.MustGetString(cmd, flagClientMetadata)), Owner: pointerx.String(flagx.MustGetString(cmd, flagClientOwner)), PolicyUri: pointerx.String(flagx.MustGetString(cmd, flagClientPolicyURI)), PostLogoutRedirectUris: flagx.MustGetStringSlice(cmd, flagClientPostLogoutCallback), RedirectUris: flagx.MustGetStringSlice(cmd, flagClientRedirectURI), RequestObjectSigningAlg: pointerx.String(flagx.MustGetString(cmd, flagClientRequestObjectSigningAlg)), RequestUris: flagx.MustGetStringSlice(cmd, flagClientRequestURI), ResponseTypes: flagx.MustGetStringSlice(cmd, flagClientResponseType), Scope: pointerx.String(strings.Join(flagx.MustGetStringSlice(cmd, flagClientScope), " ")), SkipConsent: pointerx.Bool(flagx.MustGetBool(cmd, flagClientSkipConsent)), SectorIdentifierUri: pointerx.String(flagx.MustGetString(cmd, flagClientSectorIdentifierURI)), SubjectType: pointerx.String(flagx.MustGetString(cmd, flagClientSubjectType)), TokenEndpointAuthMethod: pointerx.String(flagx.MustGetString(cmd, flagClientTokenEndpointAuthMethod)), TosUri: pointerx.String(flagx.MustGetString(cmd, flagClientTOSURI)), } } func registerEncryptFlags(flags *pflag.FlagSet) { // encrypt client secret options flags.String(cli.FlagEncryptionPGPKey, "", "Base64 encoded PGP encryption key for encrypting client secret.") flags.String(cli.FlagEncryptionPGPKeyURL, "", "PGP encryption key URL for encrypting client secret.") flags.String(cli.FlagEncryptionKeybase, "", "Keybase username for encrypting client secret.") } func registerClientFlags(flags *pflag.FlagSet) { flags.String(flagClientMetadata, "{}", "Metadata is an arbitrary JSON String of your choosing.") flags.String(flagClientOwner, "", "The owner of this client, typically email addresses or a user ID.") flags.StringSlice(flagClientContact, nil, "A list representing ways to contact people responsible for this client, typically email addresses.") flags.StringSlice(flagClientRequestURI, nil, "Array of request_uri values that are pre-registered by the RP for use at the OP.") flags.String(flagClientRequestObjectSigningAlg, "RS256", "Algorithm that must be used for signing Request Objects sent to the OP.") flags.String(flagClientSectorIdentifierURI, "", "URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OP. The URL references a file with a single JSON array of redirect_uri values.") flags.StringSlice(flagClientRedirectURI, []string{}, "List of allowed OAuth2 Redirect URIs.") flags.StringSlice(flagClientGrantType, []string{"authorization_code"}, "A list of allowed grant types.") flags.StringSlice(flagClientResponseType, []string{"code"}, "A list of allowed response types.") flags.StringSlice(flagClientScope, []string{}, "The scope the client is allowed to request.") flags.StringSlice(flagClientAudience, []string{}, "The audience this client is allowed to request.") flags.String(flagClientTokenEndpointAuthMethod, "client_secret_basic", "Define which authentication method the client may use at the Token Endpoint. Valid values are `client_secret_post`, `client_secret_basic`, `private_key_jwt`, and `none`.") flags.String(flagClientJWKSURI, "", "Define the URL where the JSON Web Key Set should be fetched from when performing the `private_key_jwt` client authentication method.") flags.String(flagClientPolicyURI, "", "A URL string that points to a human-readable privacy policy document that describes how the deployment organization collects, uses, retains, and discloses personal data.") flags.String(flagClientTOSURI, "", "A URL string that points to a human-readable terms of service document for the client that describes a contractual relationship between the end-user and the client that the end-user accepts when authorizing the client.") flags.String(flagClientClientURI, "", "A URL string of a web page providing information about the client") flags.String(flagClientLogoURI, "", "A URL string that references a logo for the client") flags.StringSlice(flagClientAllowedCORSOrigin, []string{}, "The list of URLs allowed to make CORS requests. Requires CORS_ENABLED.") flags.String(flagClientSubjectType, "public", "A identifier algorithm. Valid values are `public` and `pairwise`.") flags.String(flagClientSecret, "", "Provide the client's secret.") flags.String(flagClientName, "", "The client's name.") flags.StringSlice(flagClientPostLogoutCallback, []string{}, "List of allowed URLs to be redirected to after a logout.") flags.Bool(flagClientSkipConsent, false, "Boolean flag specifying whether to skip the consent screen for this client. If omitted, the default value is false.") // back-channel logout options flags.Bool(flagClientBackChannelLogoutSessionRequired, false, "Boolean flag specifying whether the client requires that a sid (session ID) Claim be included in the Logout Token to identify the client session with the OP when the backchannel-logout-callback is used. If omitted, the default value is false.") flags.String(flagClientBackchannelLogoutCallback, "", "Client URL that will cause the client to log itself out when sent a Logout Token by Hydra.") // front-channel logout options flags.Bool(flagClientFrontChannelLogoutSessionRequired, false, "Boolean flag specifying whether the client requires that a sid (session ID) Claim be included in the Logout Token to identify the client session with the OP when the frontchannel-logout-callback is used. If omitted, the default value is false.") flags.String(flagClientFrontChannelLogoutCallback, "", "Client URL that will cause the client to log itself out when rendered in an iframe by Hydra.") registerEncryptFlags(flags) }
Go
hydra/cmd/cmd_helper_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "encoding/base64" "net/http/httptest" "os" "testing" "github.com/gofrs/uuid" "github.com/go-jose/go-jose/v3" "github.com/spf13/cobra" "github.com/stretchr/testify/require" "github.com/ory/hydra/v2/client" "github.com/ory/hydra/v2/driver" "github.com/ory/hydra/v2/internal" "github.com/ory/hydra/v2/internal/testhelpers" "github.com/ory/x/cmdx" "github.com/ory/x/contextx" "github.com/ory/x/snapshotx" ) func base64EncodedPGPPublicKey(t *testing.T) string { t.Helper() gpgPublicKey, err := os.ReadFile("../test/stub/pgp.pub") if err != nil { t.Fatal(err) } return base64.StdEncoding.EncodeToString(gpgPublicKey) } func setupRoutes(t *testing.T, cmd *cobra.Command) (*httptest.Server, *httptest.Server, driver.Registry) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) reg := internal.NewMockedRegistry(t, &contextx.Default{}) public, admin := testhelpers.NewOAuth2Server(ctx, t, reg) cmdx.RegisterHTTPClientFlags(cmd.Flags()) cmdx.RegisterFormatFlags(cmd.Flags()) require.NoError(t, cmd.Flags().Set(cmdx.FlagFormat, string(cmdx.FormatJSON))) return public, admin, reg } func setup(t *testing.T, cmd *cobra.Command) driver.Registry { _, admin, reg := setupRoutes(t, cmd) require.NoError(t, cmd.Flags().Set(cmdx.FlagEndpoint, admin.URL)) require.NoError(t, cmd.Flags().Set(cmdx.FlagFormat, string(cmdx.FormatJSON))) return reg } var snapshotExcludedClientFields = []snapshotx.ExceptOpt{ snapshotx.ExceptNestedKeys("client_id"), snapshotx.ExceptNestedKeys("registration_access_token"), snapshotx.ExceptNestedKeys("registration_client_uri"), snapshotx.ExceptNestedKeys("client_secret"), snapshotx.ExceptNestedKeys("created_at"), snapshotx.ExceptNestedKeys("updated_at"), } func createClientCredentialsClient(t *testing.T, reg driver.Registry) *client.Client { return createClient(t, reg, &client.Client{ GrantTypes: []string{"client_credentials"}, TokenEndpointAuthMethod: "client_secret_basic", Secret: uuid.Must(uuid.NewV4()).String(), }) } func createClient(t *testing.T, reg driver.Registry, c *client.Client) *client.Client { if c == nil { c = &client.Client{TokenEndpointAuthMethod: "client_secret_post", Secret: uuid.Must(uuid.NewV4()).String()} } secret := c.Secret require.NoError(t, reg.ClientManager().CreateClient(context.Background(), c)) c.Secret = secret return c } func createJWK(t *testing.T, reg driver.Registry, set string, alg string) jose.JSONWebKey { c, err := reg.KeyManager().GenerateAndPersistKeySet(context.Background(), set, "", alg, "sig") require.NoError(t, err) return c.Keys[0] }
Go
hydra/cmd/cmd_import.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewImportCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "import", Short: "Import resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_import_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "bytes" "encoding/json" "errors" "fmt" "io" "os" "github.com/spf13/cobra" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/pointerx" ) func NewImportClientCmd() *cobra.Command { cmd := &cobra.Command{ Use: "oauth2-client <file-1.json> [<file-2.json> ...]", Aliases: []string{"client", "clients", "oauth2-clients"}, Short: "Import one or more OAuth 2.0 Clients from files or STDIN", Example: `Import an example OAuth2 Client: cat > ./file.json <<EOF [ { "grant_types": ["implicit"], "scope": "openid" }, { "grant_types": ["authorize_code"], "scope": "openid" } ] EOF {{ .CommandPath }} file.json Alternatively: cat file.json | {{ .CommandPath }} To encrypt an auto-generated OAuth2 Client Secret, use flags ` + "`--pgp-key`" + `, ` + "`--pgp-key-url`" + ` or ` + "`--keybase`" + ` flag, for example: {{ .CommandPath }} -n "my app" -g client_credentials -r token -a core,foobar --keybase keybase_username `, Long: `This command reads in each listed JSON file and imports their contents as a list of OAuth 2.0 Clients. The format for the JSON file is: [ { "client_secret": "...", // ... all other fields of the OAuth 2.0 Client model are allowed here } ] Please be aware that this command does not update existing clients. If the client exists already, this command will fail.`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } ek, encryptSecret, err := cli.NewEncryptionKey(cmd, nil) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Failed to load encryption key: %s", err) return cmdx.FailSilently(cmd) } streams := map[string]io.Reader{"STDIN": cmd.InOrStdin()} for _, path := range args { contents, err := os.ReadFile(path) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not open file %s: %s", path, err) return cmdx.FailSilently(cmd) } streams[path] = bytes.NewReader(contents) } clients := map[string][]hydra.OAuth2Client{} for src, stream := range streams { var current []hydra.OAuth2Client if err := json.NewDecoder(stream).Decode(&current); err != nil { if errors.Is(err, io.EOF) { continue } _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not decode JSON: %s", err) return cmdx.FailSilently(cmd) } clients[src] = append(clients[src], current...) } imported := make([]hydra.OAuth2Client, 0, len(clients)) failed := make(map[string]error) for src, cc := range clients { for _, c := range cc { result, _, err := m.OAuth2Api.CreateOAuth2Client(cmd.Context()).OAuth2Client(c).Execute() //nolint:bodyclose if err != nil { failed[src] = cmdx.PrintOpenAPIError(cmd, err) continue } if result.ClientSecret == nil { result.ClientSecret = c.ClientSecret } if encryptSecret && result.ClientSecret != nil { enc, err := ek.Encrypt([]byte(*result.ClientSecret)) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Failed to encrypt client secret: %s", err) return cmdx.FailSilently(cmd) } result.ClientSecret = pointerx.String(enc.Base64Encode()) } imported = append(imported, *result) } } if len(imported) == 1 { cmdx.PrintRow(cmd, (*outputOAuth2Client)(&imported[0])) } else { cmdx.PrintTable(cmd, &outputOAuth2ClientCollection{clients: imported}) } if len(failed) != 0 { cmdx.PrintErrors(cmd, failed) return cmdx.FailSilently(cmd) } return nil }, } registerEncryptFlags(cmd.Flags()) return cmd }
Go
hydra/cmd/cmd_import_client_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "bytes" "context" "encoding/json" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" "github.com/ory/x/pointerx" "github.com/ory/x/snapshotx" ) func writeTempFile(t *testing.T, contents interface{}) string { t.Helper() ij, err := json.Marshal(contents) require.NoError(t, err) f, err := os.CreateTemp(t.TempDir(), "") require.NoError(t, err) _, err = f.Write(ij) require.NoError(t, err) require.NoError(t, f.Close()) return f.Name() } func TestImportClient(t *testing.T) { ctx := context.Background() c := cmd.NewImportClientCmd() reg := setup(t, c) file1 := writeTempFile(t, []hydra.OAuth2Client{{Scope: pointerx.String("foo")}, {Scope: pointerx.String("bar"), ClientSecret: pointerx.String("some-secret")}}) file2 := writeTempFile(t, []hydra.OAuth2Client{{Scope: pointerx.String("baz")}, {Scope: pointerx.String("zab"), ClientSecret: pointerx.String("some-secret")}}) t.Run("case=imports clients from single file", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, file1)) require.Len(t, actual.Array(), 2) assert.NotEmpty(t, actual.Get("0.client_id").String()) assert.NotEmpty(t, actual.Get("0.client_secret").String()) assert.Equal(t, "some-secret", actual.Get("1.client_secret").String()) _, err := reg.ClientManager().GetClient(ctx, actual.Get("0.client_id").String()) require.NoError(t, err) _, err = reg.ClientManager().GetClient(ctx, actual.Get("1.client_id").String()) require.NoError(t, err) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) t.Run("case=imports clients from multiple files", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, file1, file2)) require.Len(t, actual.Array(), 4) for _, v := range []string{ "foo", "bar", "baz", "zab", } { found := false for _, j := range actual.Array() { if j.Get("scope").String() == v { found = true break } } assert.True(t, found, "missing client with scope %s", v) } }) t.Run("case=imports clients from multiple files and stdin", func(t *testing.T) { var stdin bytes.Buffer require.NoError(t, json.NewEncoder(&stdin).Encode([]hydra.OAuth2Client{{Scope: pointerx.String("oof")}, {Scope: pointerx.String("rab"), ClientSecret: pointerx.String("some-secret")}})) stdout, _, err := cmdx.Exec(t, c, &stdin, file1, file2) require.NoError(t, err) actual := gjson.Parse(stdout) require.Len(t, actual.Array(), 6) var found bool for _, v := range actual.Array() { if v.Get("scope").String() == "oof" { found = true } } assert.True(t, found) }) t.Run("case=performs appropriate error reporting", func(t *testing.T) { file3 := writeTempFile(t, []hydra.OAuth2Client{{ClientSecret: pointerx.String("short")}}) stdout, stderr, err := cmdx.Exec(t, c, nil, file1, file3) require.Error(t, err) actual := gjson.Parse(stdout) require.Len(t, actual.Array(), 2) assert.Contains(t, stderr, "secret that is at least 6 characters long") snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) }
Go
hydra/cmd/cmd_import_jwk.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "bytes" "encoding/json" "fmt" "io" "os" "github.com/gofrs/uuid" "github.com/spf13/cobra" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/ory/x/josex" ) func NewKeysImportCmd() *cobra.Command { cmd := &cobra.Command{ Use: "jwk set-id file-1 [file-2] [file-n]", Args: cobra.MinimumNArgs(1), Example: `{{ .CommandPath }} my-set ./path/to/jwk.json ./path/to/jwk-2.json --format json {{ .CommandPath }} my-set ./path/to/rsa.key ./path/to/rsa.pub --use enc`, Short: "Imports JSON Web Keys from one or more JSON files.", Long: `This command allows you to import JSON Web Keys from one or more JSON files or STDIN to the JSON Web Key Store. Currently supported formats are raw JSON Web Keys or PEM/DER encoded data. If the JSON Web Key Set exists already, the imported keys will be added to that set. Otherwise, a new set will be created.`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } set := args[0] streams := map[string]io.Reader{} if len(args) == 1 { streams["STDIN"] = cmd.InOrStdin() } else { for _, path := range args[1:] { contents, err := os.ReadFile(path) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not open file %s: %s", path, err) return cmdx.FailSilently(cmd) } streams[path] = bytes.NewReader(contents) } } keys := map[string][]hydra.JsonWebKey{} for src, stream := range streams { content, err := io.ReadAll(stream) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not read from %s: %s", src, err) return cmdx.FailSilently(cmd) } var key interface{} if priv, privErr := josex.LoadPrivateKey(content); privErr == nil { key = priv } else if pub, pubErr := josex.LoadPublicKey(content); pubErr == nil { key = pub } else { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not decode key from `%s` to public nor private keys: %s; %s", src, privErr, pubErr) } key = cli.ToSDKFriendlyJSONWebKey(key, "", "") var buf bytes.Buffer var jsonWebKey hydra.JsonWebKey if err := json.NewEncoder(&buf).Encode(key); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not encode key from `%s` to JSON: %s", src, err) return cmdx.FailSilently(cmd) } if err := json.NewDecoder(&buf).Decode(&jsonWebKey); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not decode key from `%s` to JSON: %s", src, err) return cmdx.FailSilently(cmd) } if len(jsonWebKey.Kid) == 0 { jsonWebKey.Kid = uuid.Must(uuid.NewV4()).String() } if len(jsonWebKey.Alg) == 0 { jsonWebKey.Alg = flagx.MustGetString(cmd, "alg") } if len(jsonWebKey.Alg) == 0 { _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Flag `--alg` is required when imported key does not define the `alg` field itself.") return cmdx.FailSilently(cmd) } if len(jsonWebKey.Use) == 0 { jsonWebKey.Use = flagx.MustGetString(cmd, "use") } if len(jsonWebKey.Use) == 0 { _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Flag `--use` is required when imported key does not define the `use` field itself.") return cmdx.FailSilently(cmd) } keys[src] = append(keys[src], jsonWebKey) } imported := make([]hydra.JsonWebKey, 0, len(keys)) failed := make(map[string]error) for src, kk := range keys { for _, k := range kk { result, _, err := m.JwkApi.SetJsonWebKey(cmd.Context(), set, k.Kid).JsonWebKey(k).Execute() //nolint:bodyclose if err != nil { failed[src] = cmdx.PrintOpenAPIError(cmd, err) continue } imported = append(imported, *result) } } cmdx.PrintTable(cmd, &outputJSONWebKeyCollection{Set: set, Keys: imported}) if len(failed) != 0 { cmdx.PrintErrors(cmd, failed) return cmdx.FailSilently(cmd) } return nil }, } cmd.Flags().String("use", "sig", "Sets the \"use\" value of the JSON Web Key if no \"use\" value was defined by the key itself. Required when importing PEM/DER encoded data.") cmd.Flags().String("alg", "", "Sets the \"alg\" value of the JSON Web Key if not \"alg\" value was defined by the key itself. Required when importing PEM/DER encoded data.") return cmd }
Go
hydra/cmd/cmd_import_jwk_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "bytes" "encoding/json" "testing" "github.com/gofrs/uuid" "github.com/stretchr/testify/require" "github.com/ory/x/snapshotx" "github.com/ory/x/stringsx" "github.com/stretchr/testify/assert" "github.com/tidwall/gjson" _ "embed" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) //go:embed stub/jwk.json var stubJsonWebKeySet []byte func TestImportJWKS(t *testing.T) { c := cmd.NewKeysImportCmd() _ = setup(t, c) t.Run("case=imports without alg fails", func(t *testing.T) { result := cmdx.ExecExpectedErr(t, c, uuid.Must(uuid.NewV4()).String(), "stub/ecdh.key") assert.Contains(t, result, "Flag `--alg` is required when imported key does not define the `alg` field itself.") }) for _, tc := range [][2]string{ {"ES256", "stub/ecdh.key"}, {"ES384", "stub/ecdh.key"}, {"ES256", "stub/ecdh.pub"}, {"RS256", "stub/rsa.key"}, {"RS256", "stub/rsa.pub"}, {"RS512", "stub/rsa.pub"}, {"", "stub/jwk.json"}, } { t.Run("case=imports encoded "+tc[1]+" key from file", func(t *testing.T) { args := []string{uuid.Must(uuid.NewV4()).String(), tc[1]} if len(tc[0]) > 0 { args = append(args, "--alg", tc[0]) } actual := gjson.Parse(cmdx.ExecNoErr(t, c, args...)) assert.Len(t, actual.Get("keys.0").Array(), 1, "%s", actual.Raw) assert.NotEmpty(t, actual.Get("keys.0.kid").String(), "%s", actual.Raw) assert.NotEmpty(t, stringsx.Coalesce(actual.Get("keys.0.x").String(), actual.Get("keys.0.n").String()), "%s", actual.Raw) assert.Equal(t, stringsx.Coalesce(tc[0], "RS256"), actual.Get("keys.0.alg").String(), "%s", actual.Raw) }) } t.Run("case=imports JWK key from STDIN", func(t *testing.T) { stdin := bytes.NewBuffer(stubJsonWebKeySet) stdout, stderr, err := cmdx.Exec(t, c, stdin, uuid.Must(uuid.NewV4()).String()) require.NoError(t, err, stderr) snapshotx.SnapshotT(t, json.RawMessage(stdout), snapshotx.ExceptNestedKeys("set", "kid")) }) }
Go
hydra/cmd/cmd_introspect.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewIntrospectCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "introspect", Short: "Introspect resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_introspect_token.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "strings" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/spf13/cobra" ) func NewIntrospectTokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token the-token", Args: cobra.ExactArgs(1), Example: `{{ .CommandPath }} AYjcyMzY3ZDhiNmJkNTY --project 32197be3-8e57-4009-becd-9d38dbde129c`, Short: "Introspect an OAuth 2.0 Access or Refresh Token", RunE: func(cmd *cobra.Command, args []string) error { client, _, err := cliclient.NewClient(cmd) if err != nil { return err } result, _, err := client.OAuth2Api.IntrospectOAuth2Token(cmd.Context()). Token(args[0]). Scope(strings.Join(flagx.MustGetStringSlice(cmd, "scope"), " ")).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } cmdx.PrintRow(cmd, outputOAuth2TokenIntrospection(*result)) return nil }, } cmd.Flags().StringSlice("scope", []string{}, "Additionally check if the scope was granted.") return cmd }
Go
hydra/cmd/cmd_introspect_token_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "testing" "golang.org/x/oauth2/clientcredentials" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) func TestIntrospectToken(t *testing.T) { c := cmd.NewIntrospectTokenCmd() public, admin, reg := setupRoutes(t, c) require.NoError(t, c.Flags().Set(cmdx.FlagEndpoint, admin.URL)) expected := createClientCredentialsClient(t, reg) cc := clientcredentials.Config{ ClientID: expected.GetID(), ClientSecret: expected.Secret, TokenURL: public.URL + "/oauth2/token", Scopes: []string{}, } t.Run("case=checks valid token", func(t *testing.T) { token, err := cc.Token(context.Background()) require.NoError(t, err) actual := gjson.Parse(cmdx.ExecNoErr(t, c, token.AccessToken)) assert.Equal(t, expected.GetID(), actual.Get("sub").String()) assert.Equal(t, expected.GetID(), actual.Get("client_id").String()) assert.True(t, actual.Get("active").Bool()) }) t.Run("case=checks invalid token", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, "invalid-token")) assert.Empty(t, actual.Get("sub").String()) assert.Empty(t, actual.Get("client_id").String()) assert.False(t, actual.Get("active").Bool()) }) }
Go
hydra/cmd/cmd_list.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewListCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "List resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_list_clients.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" ) func NewListClientsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "oauth2-clients", Aliases: []string{"clients"}, Short: "List OAuth 2.0 Clients", Long: `This command list an OAuth 2.0 Clients.`, Args: cobra.NoArgs, Example: fmt.Sprintf("{{ .CommandPath }} --%s eyJwYWdlIjoxfQ --%s 10", cmdx.FlagPageToken, cmdx.FlagPageSize), RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } pageToken, pageSize, err := cmdx.ParseTokenPaginationArgs(cmd) if err != nil { return err } // nolint:bodyclose list, resp, err := m.OAuth2Api.ListOAuth2Clients(cmd.Context()).PageSize(int64(pageSize)).PageToken(pageToken).Execute() if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } defer resp.Body.Close() var collection outputOAuth2ClientCollection collection.clients = append(collection.clients, list...) interfaceList := make([]interface{}, len(list)) for k := range collection.clients { interfaceList[k] = interface{}(&list[k]) } result := &cmdx.PaginatedList{Items: interfaceList, Collection: collection} result.NextPageToken = getPageToken(resp) result.IsLastPage = result.NextPageToken == "" cmdx.PrintTable(cmd, result) return nil }, } cmdx.RegisterTokenPaginationFlags(cmd) return cmd }
Go
hydra/cmd/cmd_list_clients_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "testing" "github.com/stretchr/testify/require" "github.com/ory/hydra/v2/client" "github.com/stretchr/testify/assert" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) func TestListClient(t *testing.T) { c := cmd.NewListClientsCmd() reg := setup(t, c) expected1 := createClient(t, reg, nil) expected2 := createClient(t, reg, nil) t.Run("case=lists both clients", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c)) assert.Len(t, actual.Get("items").Array(), 2) for _, e := range []*client.Client{expected1, expected2} { assert.Contains(t, actual.Raw, e.GetID()) } }) t.Run("case=lists both clients with pagination", func(t *testing.T) { actualFirst := gjson.Parse(cmdx.ExecNoErr(t, c, "--format", "json", "--page-size", "1")) assert.Len(t, actualFirst.Get("items").Array(), 1) require.NotEmpty(t, actualFirst.Get("next_page_token").String(), actualFirst.Raw) assert.False(t, actualFirst.Get("is_last_page").Bool(), actualFirst.Raw) actualSecond := gjson.Parse(cmdx.ExecNoErr(t, c, "--format", "json", "--page-size", "1", "--page-token", actualFirst.Get("next_page_token").String())) assert.Len(t, actualSecond.Array(), 1) assert.NotEmpty(t, actualFirst.Get("items.0.client_id").String()) assert.NotEqualValues(t, actualFirst.Get("items.0.client_id").String(), actualSecond.Get("items.0.client_id").String()) }) }
Go
hydra/cmd/cmd_perform.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewPerformCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "perform", Short: "Perform OAuth 2.0 Flows", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_perform_authorization_code.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "context" "crypto/rand" "crypto/rsa" "crypto/tls" "fmt" "html/template" "net/http" "os" "strconv" "strings" "time" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/pkg/errors" "github.com/ory/graceful" "github.com/julienschmidt/httprouter" "github.com/spf13/cobra" "github.com/toqueteos/webbrowser" "golang.org/x/oauth2" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/ory/x/randx" "github.com/ory/x/tlsx" "github.com/ory/x/urlx" ) var tokenUserWelcome = template.Must(template.New("").Parse(`<html> <body> <h1>Welcome to the exemplary OAuth 2.0 Consumer!</h1> <p>This is an example app which emulates an OAuth 2.0 consumer application. Usually, this would be your web or mobile application and would use an <a href="https://oauth.net/code/">OAuth 2.0</a> or <a href="https://oauth.net/code/">OpenID Connect</a> library.</p> <p>This example requests an OAuth 2.0 Access, Refresh, and OpenID Connect ID Token from the OAuth 2.0 Server (Ory Hydra). To initiate the flow, click the "Authorize Application" button.</p> <p><a href="{{ .URL }}">Authorize application</a></p> </body> </html>`)) var tokenUserError = template.Must(template.New("").Parse(`<html> <body> <h1>An error occurred</h1> <h2>{{ .Name }}</h2> <p>{{ .Description }}</p> <p>{{ .Hint }}</p> <p>{{ .Debug }}</p> </body> </html>`)) var tokenUserResult = template.Must(template.New("").Parse(`<html> <head></head> <body> <ul> <li>Access Token: <code>{{ .AccessToken }}</code></li> <li>Refresh Token: <code>{{ .RefreshToken }}</code></li> <li>Expires in: <code>{{ .Expiry }}</code></li> <li>ID Token: <code>{{ .IDToken }}</code></li> </ul> {{ if .DisplayBackButton }} <a href="{{ .BackURL }}">Back to Welcome PageToken</a> {{ end }} </body> </html>`)) func NewPerformAuthorizationCodeCmd() *cobra.Command { cmd := &cobra.Command{ Use: "authorization-code", Example: "{{ .CommandPath }} --client-id ... --client-secret ...", Short: "An exemplary OAuth 2.0 Client performing the OAuth 2.0 Authorize Code Flow", Long: `Starts an exemplary web server that acts as an OAuth 2.0 Client performing the Authorize Code Flow. This command will help you to see if Ory Hydra has been configured properly. This command must not be used for anything else than manual testing or demo purposes. The server will terminate on error and success, unless if the --no-shutdown flag is provided.`, RunE: func(cmd *cobra.Command, args []string) error { client, endpoint, err := cliclient.NewClient(cmd) if err != nil { return err } endpoint = cliclient.GetOAuth2URLOverride(cmd, endpoint) ctx := context.WithValue(cmd.Context(), oauth2.HTTPClient, client) isSSL := flagx.MustGetBool(cmd, "https") port := flagx.MustGetInt(cmd, "port") scopes := flagx.MustGetStringSlice(cmd, "scope") prompt := flagx.MustGetStringSlice(cmd, "prompt") maxAge := flagx.MustGetInt(cmd, "max-age") redirectUrl := flagx.MustGetString(cmd, "redirect") authUrl := flagx.MustGetString(cmd, "auth-url") tokenUrl := flagx.MustGetString(cmd, "token-url") audience := flagx.MustGetStringSlice(cmd, "audience") noShutdown := flagx.MustGetBool(cmd, "no-shutdown") clientID := flagx.MustGetString(cmd, "client-id") if clientID == "" { _, _ = fmt.Fprint(cmd.OutOrStdout(), cmd.UsageString()) _, _ = fmt.Fprintln(cmd.OutOrStdout(), "Please provide a Client ID using --client-id flag, or OAUTH2_CLIENT_ID environment variable.") return cmdx.FailSilently(cmd) } clientSecret := flagx.MustGetString(cmd, "client-secret") proto := "http" if isSSL { proto = "https" } serverLocation := fmt.Sprintf("%s://127.0.0.1:%d/", proto, port) if redirectUrl == "" { redirectUrl = serverLocation + "callback" } if authUrl == "" { authUrl = urlx.AppendPaths(endpoint, "/oauth2/auth").String() } if tokenUrl == "" { tokenUrl = urlx.AppendPaths(endpoint, "/oauth2/token").String() } conf := oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, Endpoint: oauth2.Endpoint{ AuthURL: authUrl, TokenURL: tokenUrl, }, RedirectURL: redirectUrl, Scopes: scopes, } var generateAuthCodeURL = func() (string, string) { state := flagx.MustGetString(cmd, "state") if len(state) == 0 { generatedState, err := randx.RuneSequence(24, randx.AlphaLower) cmdx.Must(err, "Could not generate random state: %s", err) state = string(generatedState) } nonce, err := randx.RuneSequence(24, randx.AlphaLower) cmdx.Must(err, "Could not generate random state: %s", err) authCodeURL := conf.AuthCodeURL( state, oauth2.SetAuthURLParam("audience", strings.Join(audience, "+")), oauth2.SetAuthURLParam("nonce", string(nonce)), oauth2.SetAuthURLParam("prompt", strings.Join(prompt, "+")), oauth2.SetAuthURLParam("max_age", strconv.Itoa(maxAge)), ) return authCodeURL, state } authCodeURL, state := generateAuthCodeURL() if !flagx.MustGetBool(cmd, "no-open") { _ = webbrowser.Open(serverLocation) // ignore errors } _, _ = fmt.Fprintln(os.Stderr, "Setting up home route on "+serverLocation) _, _ = fmt.Fprintln(os.Stderr, "Setting up callback listener on "+serverLocation+"callback") _, _ = fmt.Fprintln(os.Stderr, "Press ctrl + c on Linux / Windows or cmd + c on OSX to end the process.") _, _ = fmt.Fprintf(os.Stderr, "If your browser does not open automatically, navigate to:\n\n\t%s\n\n", serverLocation) r := httprouter.New() var tlsc *tls.Config if isSSL { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { _, _ = fmt.Fprintf(os.Stderr, "Unable to generate RSA key pair: %s", err) return cmdx.FailSilently(cmd) } cert, err := tlsx.CreateSelfSignedTLSCertificate(key) cmdx.Must(err, "Unable to generate self-signed TLS Certificate: %s", err) // #nosec G402 - This is a false positive because we use graceful.WithDefaults which sets the correct TLS settings. tlsc = &tls.Config{Certificates: []tls.Certificate{*cert}} } server := graceful.WithDefaults(&http.Server{ Addr: fmt.Sprintf(":%d", port), Handler: r, TLSConfig: tlsc, ReadHeaderTimeout: time.Second * 5, }) var shutdown = func() { time.Sleep(time.Second * 1) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() _ = server.Shutdown(ctx) } var onDone = func() { if !noShutdown { go shutdown() } else { // regenerate because we don't want to shutdown and we don't want to reuse nonce & state authCodeURL, state = generateAuthCodeURL() } } r.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { _ = tokenUserWelcome.Execute(w, &struct{ URL string }{URL: authCodeURL}) }) r.GET("/perform-flow", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { http.Redirect(w, r, authCodeURL, http.StatusFound) }) type ed struct { Name string Description string Hint string Debug string } r.GET("/callback", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { if len(r.URL.Query().Get("error")) > 0 { _, _ = fmt.Fprintf(os.Stderr, "Got error: %s\n", r.URL.Query().Get("error_description")) w.WriteHeader(http.StatusInternalServerError) _ = tokenUserError.Execute(w, &ed{ Name: r.URL.Query().Get("error"), Description: r.URL.Query().Get("error_description"), Hint: r.URL.Query().Get("error_hint"), Debug: r.URL.Query().Get("error_debug"), }) onDone() return } if r.URL.Query().Get("state") != string(state) { _, _ = fmt.Fprintf(os.Stderr, "States do not match. Expected %s, got %s\n", string(state), r.URL.Query().Get("state")) w.WriteHeader(http.StatusInternalServerError) _ = tokenUserError.Execute(w, &ed{ Name: "States do not match", Description: "Expected state " + string(state) + " but got " + r.URL.Query().Get("state"), }) onDone() return } code := r.URL.Query().Get("code") token, err := conf.Exchange(ctx, code) if err != nil { _, _ = fmt.Fprintf(os.Stderr, "Unable to exchange code for token: %s\n", err) w.WriteHeader(http.StatusInternalServerError) _ = tokenUserError.Execute(w, &ed{ Name: err.Error(), }) onDone() return } cmdx.PrintRow(cmd, outputOAuth2Token(*token)) _ = tokenUserResult.Execute(w, struct { AccessToken string RefreshToken string Expiry string IDToken string BackURL string DisplayBackButton bool }{ AccessToken: token.AccessToken, RefreshToken: token.RefreshToken, Expiry: token.Expiry.Format(time.RFC1123), IDToken: fmt.Sprintf("%s", token.Extra("id_token")), BackURL: serverLocation, DisplayBackButton: noShutdown, }) onDone() }) if isSSL { err = server.ListenAndServeTLS("", "") } else { err = server.ListenAndServe() } if errors.Is(err, http.ErrServerClosed) { return nil } else if err != nil { return err } return nil }, } cmd.Flags().Bool("no-open", false, "Do not open the browser window automatically") cmd.Flags().IntP("port", "p", 4446, "The port on which the server should run") cmd.Flags().StringSlice("scope", []string{"offline", "openid"}, "Request OAuth2 scope") cmd.Flags().StringSlice("prompt", []string{}, "Set the OpenID Connect prompt parameter") cmd.Flags().Int("max-age", 0, "Set the OpenID Connect max_age parameter") cmd.Flags().Bool("no-shutdown", false, "Do not terminate on success/error. State and nonce will be regenerated when auth flow has completed (either due to an error or success).") cmd.Flags().String("client-id", os.Getenv("OAUTH2_CLIENT_ID"), "Use the provided OAuth 2.0 Client ID, defaults to environment variable OAUTH2_CLIENT_ID") cmd.Flags().String("client-secret", os.Getenv("OAUTH2_CLIENT_SECRET"), "Use the provided OAuth 2.0 Client Secret, defaults to environment variable OAUTH2_CLIENT_SECRET") cmd.Flags().String("state", "", "Force a state value (insecure)") cmd.Flags().String("redirect", "", "Force a redirect url") cmd.Flags().StringSlice("audience", []string{}, "Request a specific OAuth 2.0 Access Token Audience") cmd.Flags().String("auth-url", "", "Usually it is enough to specify the `endpoint` flag, but if you want to force the authorization url, use this flag") cmd.Flags().String("token-url", "", "Usually it is enough to specify the `endpoint` flag, but if you want to force the token url, use this flag") cmd.Flags().Bool("https", false, "Sets up HTTPS for the endpoint using a self-signed certificate which is re-generated every time you start this command") return cmd }
Go
hydra/cmd/cmd_perform_client_credentials.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "context" "fmt" "net/url" "os" "strings" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/spf13/cobra" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/ory/x/urlx" ) func NewPerformClientCredentialsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "client-credentials", Args: cobra.NoArgs, Example: `{{ .CommandPath }} --client-id ... --client-secret`, Short: "Perform the OAuth2 Client Credentials Flow", Long: `Performs the OAuth 2.0 Client Credentials Flow. Useful to exchange a client_id and client_secret for an access_token. using the CLI.`, RunE: func(cmd *cobra.Command, args []string) error { hc, target, err := cliclient.NewClient(cmd) if err != nil { return err } ctx := context.WithValue(cmd.Context(), oauth2.HTTPClient, hc) scopes := flagx.MustGetStringSlice(cmd, "scope") audience := flagx.MustGetStringSlice(cmd, "audience") clientID := flagx.MustGetString(cmd, "client-id") clientSecret := flagx.MustGetString(cmd, "client-secret") if clientID == "" || clientSecret == "" { fmt.Print(cmd.UsageString()) _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Please provide a Client ID and Client Secret using flags --client-id and --client-secret, or environment variables OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET.") return cmdx.FailSilently(cmd) } oauthConfig := clientcredentials.Config{ ClientID: clientID, ClientSecret: clientSecret, TokenURL: urlx.AppendPaths(target, "/oauth2/token").String(), Scopes: scopes, EndpointParams: url.Values{"audience": {strings.Join(audience, " ")}}, } t, err := oauthConfig.Token(ctx) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not retrieve access token because: %s", err) return cmdx.FailSilently(cmd) } cmdx.PrintRow(cmd, (*outputOAuth2Token)(t)) return nil }, } cmd.Flags().String("client-id", os.Getenv("OAUTH2_CLIENT_ID"), "Use the provided OAuth 2.0 Client ID, defaults to environment variable OAUTH2_CLIENT_ID.") cmd.Flags().String("client-secret", os.Getenv("OAUTH2_CLIENT_SECRET"), "Use the provided OAuth 2.0 Client Secret, defaults to environment variable OAUTH2_CLIENT_SECRET.") cmd.Flags().StringSlice("scope", []string{}, "OAuth2 scope to request.") cmd.Flags().StringSlice("audience", []string{}, "Request a specific OAuth 2.0 Access Token Audience.") return cmd }
Go
hydra/cmd/cmd_perform_client_credentials_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "testing" "github.com/stretchr/testify/require" "github.com/stretchr/testify/assert" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" ) func TestPerformClientCredentialsGrant(t *testing.T) { c := cmd.NewPerformClientCredentialsCmd() public, _, reg := setupRoutes(t, c) require.NoError(t, c.Flags().Set(cmdx.FlagEndpoint, public.URL)) expected := createClientCredentialsClient(t, reg) t.Run("case=exchanges for access token", func(t *testing.T) { result := cmdx.ExecNoErr(t, c, "--client-id", expected.ID.String(), "--client-secret", expected.Secret) actual := gjson.Parse(result) assert.Equal(t, "bearer", actual.Get("token_type").String(), result) assert.NotEmpty(t, actual.Get("access_token").String(), result) assert.NotEmpty(t, actual.Get("expiry").String(), result) assert.Empty(t, actual.Get("refresh_token").String(), result) assert.Empty(t, actual.Get("id_token").String(), result) }) }
Go
hydra/cmd/cmd_revoke.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewRevokeCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "revoke", Short: "Revoke resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_revoke_token.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "context" "fmt" "os" hydra "github.com/ory/hydra-client-go/v2" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/spf13/cobra" ) func NewRevokeTokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token the-token", Example: `{{ .CommandPath }} --client-id a0184d6c-b313-4e70-a0b9-905b581e9218 --client-secret Hh1BjioNNm ciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNT`, Args: cobra.ExactArgs(1), Short: "Revoke an access or refresh token", RunE: func(cmd *cobra.Command, args []string) error { client, _, err := cliclient.NewClient(cmd) if err != nil { return err } clientID, clientSecret := flagx.MustGetString(cmd, "client-id"), flagx.MustGetString(cmd, "client-secret") if clientID == "" || clientSecret == "" { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), `%s Please provide a Client ID and Client Secret using flags --client-id and --client-secret, or environment variables OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET `, cmd.UsageString()) return cmdx.FailSilently(cmd) } token := args[0] _, err = client.OAuth2Api.RevokeOAuth2Token( context.WithValue(cmd.Context(), hydra.ContextBasicAuth, hydra.BasicAuth{ UserName: clientID, Password: clientSecret, })).Token(token).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } cmdx.PrintRow(cmd, cmdx.OutputIder(token)) return nil }, } cmd.Flags().String("client-id", os.Getenv("OAUTH2_CLIENT_ID"), "Use the provided OAuth 2.0 Client ID, defaults to environment variable OAUTH2_CLIENT_ID") cmd.Flags().String("client-secret", os.Getenv("OAUTH2_CLIENT_SECRET"), "Use the provided OAuth 2.0 Client Secret, defaults to environment variable OAUTH2_CLIENT_SECRET") return cmd }
Go
hydra/cmd/cmd_revoke_token_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "golang.org/x/oauth2/clientcredentials" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" "github.com/ory/x/snapshotx" ) func TestRevokeToken(t *testing.T) { c := cmd.NewRevokeTokenCmd() public, _, reg := setupRoutes(t, c) require.NoError(t, c.Flags().Set(cmdx.FlagEndpoint, public.URL)) expected := createClientCredentialsClient(t, reg) cc := clientcredentials.Config{ ClientID: expected.GetID(), ClientSecret: expected.Secret, TokenURL: public.URL + "/oauth2/token", } t.Run("case=revokes valid token but without client credentials", func(t *testing.T) { token, err := cc.Token(context.Background()) require.NoError(t, err) snapshotx.SnapshotT(t, cmdx.ExecExpectedErr(t, c, token.AccessToken)) }) t.Run("case=revokes valid token", func(t *testing.T) { token, err := cc.Token(context.Background()) require.NoError(t, err) actual := gjson.Parse(cmdx.ExecNoErr(t, c, "--client-id", expected.GetID(), "--client-secret", expected.Secret, token.AccessToken)) assert.Equal(t, token.AccessToken, actual.String()) }) t.Run("case=checks invalid token", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, "invalid-token")) assert.Equal(t, "invalid-token", actual.String()) }) }
Go
hydra/cmd/cmd_update.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewUpdateCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "update", Short: "Update resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/cmd_update_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "context" "fmt" "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/hydra/v2/cmd/cliclient" "github.com/ory/x/cmdx" "github.com/ory/x/flagx" "github.com/ory/x/pointerx" ) func NewUpdateClientCmd() *cobra.Command { cmd := &cobra.Command{ Use: "oauth2-client [id]", Aliases: []string{"client"}, Short: "Update an OAuth 2.0 Client", Args: cobra.ExactArgs(1), Example: `{{ .CommandPath }} <client-id-here> -c http://localhost/cb -g authorization_code -r code -a core,foobar To encrypt an auto-generated OAuth2 Client Secret, use flags ` + "`--pgp-key`" + `, ` + "`--pgp-key-url`" + ` or ` + "`--keybase`" + ` flag, for example: {{ .CommandPath }} e6e96aa5-9cd2-4a70-bf56-ad6434c8aaa2 -n "my app" -g client_credentials -r token -a core,foobar --keybase keybase_username `, Long: `This command replaces an OAuth 2.0 Client by its ID. Please be aware that this command replaces the entire client. If only the name flag (-n "my updated app") is provided, the all other fields are updated to their default values.`, RunE: func(cmd *cobra.Command, args []string) error { m, _, err := cliclient.NewClient(cmd) if err != nil { return err } secret := flagx.MustGetString(cmd, "secret") ek, encryptSecret, err := cli.NewEncryptionKey(cmd, nil) if err != nil { return err } id := args[0] cc := clientFromFlags(cmd) client, _, err := m.OAuth2Api.SetOAuth2Client(context.Background(), id).OAuth2Client(cc).Execute() //nolint:bodyclose if err != nil { return cmdx.PrintOpenAPIError(cmd, err) } if client.ClientSecret == nil && len(secret) > 0 { client.ClientSecret = pointerx.String(secret) } if encryptSecret && client.ClientSecret != nil { enc, err := ek.Encrypt([]byte(*client.ClientSecret)) if err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Failed to encrypt client secret: %s", err) return cmdx.FailSilently(cmd) } client.ClientSecret = pointerx.String(enc.Base64Encode()) } cmdx.PrintRow(cmd, (*outputOAuth2Client)(client)) return nil }, } registerClientFlags(cmd.Flags()) return cmd }
Go
hydra/cmd/cmd_update_client_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd_test import ( "context" "encoding/json" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/hydra/v2/cmd" "github.com/ory/x/cmdx" "github.com/ory/x/snapshotx" ) func TestUpdateClient(t *testing.T) { ctx := context.Background() c := cmd.NewUpdateClientCmd() reg := setup(t, c) original := createClient(t, reg, nil) t.Run("case=creates successfully", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, "--grant-type", "implicit", original.ID.String())) expected, err := reg.ClientManager().GetClient(ctx, actual.Get("client_id").String()) require.NoError(t, err) assert.Equal(t, expected.GetID(), actual.Get("client_id").String()) assert.Equal(t, "implicit", actual.Get("grant_types").Array()[0].String()) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) t.Run("case=supports encryption", func(t *testing.T) { actual := gjson.Parse(cmdx.ExecNoErr(t, c, original.ID.String(), "--secret", "some-userset-secret", "--pgp-key", base64EncodedPGPPublicKey(t), )) assert.NotEmpty(t, actual.Get("client_id").String()) assert.NotEmpty(t, actual.Get("client_secret").String()) snapshotx.SnapshotT(t, json.RawMessage(actual.Raw), snapshotExcludedClientFields...) }) }
Go
hydra/cmd/create.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/cmdx" ) func NewCreateCmd() *cobra.Command { var cmd = &cobra.Command{ Use: "create", Short: "Create resources", } cmdx.RegisterHTTPClientFlags(cmd.PersistentFlags()) cmdx.RegisterFormatFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/helper.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "net/http" "net/url" "os" "github.com/tomnomnom/linkheader" ) var osExit = os.Exit func fatal(message string, args ...interface{}) { fmt.Printf(message+"\n", args...) osExit(1) } func getPageToken(resp *http.Response) string { for _, link := range linkheader.Parse(resp.Header.Get("Link")) { if link.Rel != "next" { continue } parsed, err := url.Parse(link.URL) if err != nil { continue } if pageToken := parsed.Query().Get("page_token"); len(pageToken) > 0 { return pageToken } } return "" }
Go
hydra/cmd/helper_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "net/http/httptest" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/ory/x/pagination/tokenpagination" ) func TestFatal(t *testing.T) { oldOsExit := osExit defer func() { osExit = oldOsExit }() var got int myExit := func(code int) { got = code } osExit = myExit fatal("Fatal message") if exp := 1; got != exp { t.Errorf("Expected exit code: %d, got: %d", exp, got) } } func TestGetPageToken(t *testing.T) { u, _ := url.Parse("https://example.com/foobar") rec := httptest.NewRecorder() tokenpagination.PaginationHeader(rec, u, 100, 3, 10) assert.Equal(t, `eyJvZmZzZXQiOiI0MCIsInYiOjJ9`, getPageToken(rec.Result()), rec.Result().Header.Get("Link")) }
Go
hydra/cmd/janitor.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/servicelocatorx" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/x/configx" ) func NewJanitorCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { cmd := &cobra.Command{ Use: "janitor [<database-url>]", Short: "This command cleans up stale database rows.", Example: `hydra janitor --keep-if-younger 23h --access-lifespan 1h --refresh-lifespan 40h --consent-request-lifespan 10m <database-url>`, Long: `This command cleans up stale database rows. This will select records to delete with a limit and delete records in batch to ensure that no table locking issues arise in big production databases. ### Warning ### This command is irreversible. Proceed with caution! This is a destructive command and will purge data directly from the database. Please use this command with caution. ############### Janitor can be used in several ways. 1. By passing the database connection string (DSN) as an argument Pass the database url (dsn) as an argument to janitor. E.g. janitor {database-url} 2. By passing the DSN as an environment variable export DSN=... janitor -e 3. By passing a configuration file containing the DSN janitor -c /path/to/conf.yml 4. Extra *optional* parameters can also be added such as hydra janitor --keep-if-younger 23h --access-lifespan 1h --refresh-lifespan 40h --consent-request-lifespan 10m {database-url} 5. Running only a certain cleanup hydra janitor --tokens {database-url} or hydra janitor --requests {database-url} or hydra janitor --grants {database-url} or any combination of them hydra janitor --tokens --requests --grants {database-url} `, RunE: cli.NewHandler(slOpts, dOpts, cOpts).Janitor.RunE, Args: cli.NewHandler(slOpts, dOpts, cOpts).Janitor.Args, } cmd.Flags().Int(cli.Limit, 10000, "Limit the number of records retrieved from database for deletion.") cmd.Flags().Int(cli.BatchSize, 100, "Define how many records are deleted with each iteration.") cmd.Flags().Duration(cli.KeepIfYounger, 0, "Keep database records that are younger than a specified duration e.g. 1s, 1m, 1h.") cmd.Flags().Duration(cli.AccessLifespan, 0, "Set the access token lifespan e.g. 1s, 1m, 1h.") cmd.Flags().Duration(cli.RefreshLifespan, 0, "Set the refresh token lifespan e.g. 1s, 1m, 1h.") cmd.Flags().Duration(cli.ConsentRequestLifespan, 0, "Set the login/consent request lifespan e.g. 1s, 1m, 1h") cmd.Flags().Bool(cli.OnlyRequests, false, "This will only run the cleanup on requests and will skip token and trust relationships cleanup.") cmd.Flags().Bool(cli.OnlyTokens, false, "This will only run the cleanup on tokens and will skip requests and trust relationships cleanup.") cmd.Flags().Bool(cli.OnlyGrants, false, "This will only run the cleanup on trust relationships and will skip requests and token cleanup.") cmd.Flags().BoolP(cli.ReadFromEnv, "e", false, "If set, reads the database connection string from the environment variable DSN or config file key dsn.") configx.RegisterFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/migrate.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/configx" ) func NewMigrateCmd() *cobra.Command { cmd := &cobra.Command{ Use: "migrate", Short: "Various migration helpers", } configx.RegisterFlags(cmd.PersistentFlags()) return cmd }
Go
hydra/cmd/migrate_gen.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cli" ) func NewMigrateGenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "gen </source/path> </target/path>", Short: "Generate migration files from migration templates", Run: cli.NewHandler(nil, nil, nil).Migration.MigrateGen, } cmd.Flags().StringSlice("dialects", []string{"sqlite", "cockroach", "mysql", "postgres"}, "Expect migrations for these dialects and no others to be either explicitly defined, or to have a generic fallback. \"\" disables dialect validation.") return cmd }
Go
hydra/cmd/migrate_sql.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/cli" ) func NewMigrateSqlCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { cmd := &cobra.Command{ Use: "sql <database-url>", Short: "Create SQL schemas and apply migration plans", Long: `Run this command on a fresh SQL installation and when you upgrade Hydra to a new minor version. For example, upgrading Hydra 0.7.0 to 0.8.0 requires running this command. It is recommended to run this command close to the SQL instance (e.g. same subnet) instead of over the public internet. This decreases risk of failure and decreases time required. You can read in the database URL using the -e flag, for example: export DSN=... hydra migrate sql -e ### WARNING ### Before running this command on an existing database, create a back up!`, RunE: cli.NewHandler(slOpts, dOpts, cOpts).Migration.MigrateSQL, } cmd.Flags().BoolP("read-from-env", "e", false, "If set, reads the database connection string from the environment variable DSN or config file key dsn.") cmd.Flags().BoolP("yes", "y", false, "If set all confirmation requests are accepted without user interaction.") return cmd }
Go
hydra/cmd/migrate_status.go
// Copyright © 2023 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/ory/x/cmdx" "github.com/ory/x/configx" "github.com/ory/x/servicelocatorx" "github.com/spf13/cobra" "github.com/ory/hydra/v2/cmd/cli" "github.com/ory/hydra/v2/driver" ) func NewMigrateStatusCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { cmd := &cobra.Command{ Use: "status", Short: "Get the current migration status", RunE: cli.NewHandler(slOpts, dOpts, cOpts).Migration.MigrateStatus, } cmdx.RegisterFormatFlags(cmd.PersistentFlags()) cmd.Flags().BoolP("read-from-env", "e", false, "If set, reads the database connection string from the environment variable DSN or config file key dsn.") cmd.Flags().Bool("block", false, "Block until all migrations have been applied") return cmd }
Go
hydra/cmd/output_client.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "strings" "github.com/ory/x/pointerx" hydra "github.com/ory/hydra-client-go/v2" ) type ( outputOAuth2Client hydra.OAuth2Client outputOAuth2ClientCollection struct { clients []hydra.OAuth2Client } ) func (outputOAuth2Client) Header() []string { return []string{"CLIENT ID", "CLIENT SECRET", "GRANT TYPES", "RESPONSE TYPES", "SCOPE", "AUDIENCE", "REDIRECT URIS"} } func (i outputOAuth2Client) Columns() []string { data := [7]string{ fmt.Sprintf("%v", pointerx.StringR(i.ClientId)), fmt.Sprintf("%v", pointerx.StringR(i.ClientSecret)), strings.Join(i.GrantTypes, ", "), strings.Join(i.ResponseTypes, ", "), fmt.Sprintf("%v", pointerx.StringR(i.Scope)), strings.Join(i.Audience, ","), strings.Join(i.RedirectUris, ", "), } return data[:] } func (i outputOAuth2Client) Interface() interface{} { return i } func (outputOAuth2ClientCollection) Header() []string { return outputOAuth2Client{}.Header() } func (c outputOAuth2ClientCollection) Table() [][]string { rows := make([][]string, len(c.clients)) for i, client := range c.clients { rows[i] = outputOAuth2Client(client).Columns() } return rows } func (c outputOAuth2ClientCollection) Interface() interface{} { return c.clients } func (c outputOAuth2ClientCollection) Len() int { return len(c.clients) } func (c outputOAuth2ClientCollection) IDs() []string { ids := make([]string, len(c.clients)) for i, client := range c.clients { ids[i] = fmt.Sprintf("%v", client.ClientId) } return ids }
Go
hydra/cmd/output_introspection.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "time" "github.com/ory/x/pointerx" hydra "github.com/ory/hydra-client-go/v2" ) type ( outputOAuth2TokenIntrospection hydra.IntrospectedOAuth2Token ) func (outputOAuth2TokenIntrospection) Header() []string { return []string{"ACTIVE", "SUBJECT", "CLIENT ID", "SCOPE", "EXPIRY", "TOKEN USE"} } func (i outputOAuth2TokenIntrospection) Columns() []string { if i.Sub == nil { i.Sub = pointerx.String("") } if i.ClientId == nil { i.ClientId = pointerx.String("") } if i.Scope == nil { i.Scope = pointerx.String("") } if i.TokenUse == nil { i.TokenUse = pointerx.String("") } if i.Exp == nil { i.Exp = pointerx.Int64(0) } return []string{ fmt.Sprintf("%v", i.Active), fmt.Sprintf("%v", *i.Sub), fmt.Sprintf("%v", *i.ClientId), fmt.Sprintf("%v", *i.Scope), fmt.Sprintf("%v", time.Unix(*i.Exp, 0).String()), fmt.Sprintf("%v", *i.TokenUse), } } func (i outputOAuth2TokenIntrospection) Interface() interface{} { return i }
Go
hydra/cmd/output_jwks.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" hydra "github.com/ory/hydra-client-go/v2" ) type ( outputJsonWebKey struct { Set string `json:"set"` hydra.JsonWebKey } outputJSONWebKeyCollection struct { Set string `json:"set"` Keys []hydra.JsonWebKey `json:"keys"` } ) func (outputJsonWebKey) Header() []string { return []string{"SET ID", "KEY ID", "ALGORITHM", "USE"} } func (i outputJsonWebKey) Columns() []string { data := [7]string{ i.Set, i.Kid, i.Alg, i.Use, } return data[:] } func (i outputJsonWebKey) Interface() interface{} { return i } func (outputJSONWebKeyCollection) Header() []string { return outputJsonWebKey{}.Header() } func (c outputJSONWebKeyCollection) Table() [][]string { rows := make([][]string, len(c.Keys)) for i, key := range c.Keys { rows[i] = outputJsonWebKey{Set: c.Set, JsonWebKey: key}.Columns() } return rows } func (c outputJSONWebKeyCollection) Interface() interface{} { return c } func (c outputJSONWebKeyCollection) Len() int { return len(c.Keys) } func (c outputJSONWebKeyCollection) IDs() []string { ids := make([]string, len(c.Keys)) for i, client := range c.Keys { ids[i] = fmt.Sprintf("%v", client.Kid) } return ids }
Go
hydra/cmd/output_token.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "time" "github.com/ory/x/stringsx" "golang.org/x/oauth2" ) type ( outputOAuth2Token oauth2.Token ) func (outputOAuth2Token) Header() []string { return []string{"ACCESS TOKEN", "REFRESH TOKEN", "ID TOKEN", "EXPIRY"} } func (i outputOAuth2Token) Columns() []string { token := oauth2.Token(i) printIDToken := "<empty>" if idt := token.Extra("id_token"); idt != nil { printIDToken = fmt.Sprintf("%s", token.Extra("id_token")) } return []string{ i.AccessToken, stringsx.Coalesce(i.RefreshToken, "<empty>"), printIDToken, i.Expiry.Round(time.Second).String(), } } func (i outputOAuth2Token) Interface() interface{} { return i }
Go
hydra/cmd/root.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "fmt" "os" "github.com/ory/x/cmdx" "github.com/ory/hydra/v2/driver" "github.com/ory/x/configx" "github.com/ory/x/servicelocatorx" "github.com/spf13/cobra" ) func NewRootCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { cmd := &cobra.Command{ Use: "hydra", Short: "Run and manage Ory Hydra", } cmdx.EnableUsageTemplating(cmd) RegisterCommandRecursive(cmd, slOpts, dOpts, cOpts) return cmd } func RegisterCommandRecursive(parent *cobra.Command, slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) { createCmd := NewCreateCmd() createCmd.AddCommand( NewCreateClientsCommand(), NewCreateJWKSCmd(), ) getCmd := NewGetCmd() getCmd.AddCommand( NewGetClientsCmd(), NewGetJWKSCmd(), ) deleteCmd := NewDeleteCmd() deleteCmd.AddCommand( NewDeleteClientCmd(), NewDeleteJWKSCommand(), NewDeleteAccessTokensCmd(), ) listCmd := NewListCmd() listCmd.AddCommand(NewListClientsCmd()) updateCmd := NewUpdateCmd() updateCmd.AddCommand(NewUpdateClientCmd()) importCmd := NewImportCmd() importCmd.AddCommand( NewImportClientCmd(), NewKeysImportCmd(), ) performCmd := NewPerformCmd() performCmd.AddCommand( NewPerformClientCredentialsCmd(), NewPerformAuthorizationCodeCmd(), ) revokeCmd := NewRevokeCmd() revokeCmd.AddCommand(NewRevokeTokenCmd()) introspectCmd := NewIntrospectCmd() introspectCmd.AddCommand(NewIntrospectTokenCmd()) migrateCmd := NewMigrateCmd() migrateCmd.AddCommand(NewMigrateGenCmd()) migrateCmd.AddCommand(NewMigrateSqlCmd(slOpts, dOpts, cOpts)) migrateCmd.AddCommand(NewMigrateStatusCmd(slOpts, dOpts, cOpts)) serveCmd := NewServeCmd() serveCmd.AddCommand(NewServeAdminCmd(slOpts, dOpts, cOpts)) serveCmd.AddCommand(NewServePublicCmd(slOpts, dOpts, cOpts)) serveCmd.AddCommand(NewServeAllCmd(slOpts, dOpts, cOpts)) parent.AddCommand( createCmd, getCmd, deleteCmd, listCmd, updateCmd, importCmd, performCmd, introspectCmd, revokeCmd, migrateCmd, serveCmd, NewJanitorCmd(slOpts, dOpts, cOpts), NewVersionCmd(), ) } // Execute adds all child commands to the root command sets flags appropriately. func Execute() { if err := NewRootCmd(nil, nil, nil).Execute(); err != nil { fmt.Println(err) os.Exit(-1) } }
Go
hydra/cmd/root_test.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "testing" "github.com/ory/x/cmdx" ) func TestUsageStrings(t *testing.T) { cmdx.AssertUsageTemplates(t, NewRootCmd(nil, nil, nil)) }
Go
hydra/cmd/serve.go
// Copyright © 2022 Ory Corp // SPDX-License-Identifier: Apache-2.0 package cmd import ( "github.com/spf13/cobra" "github.com/ory/x/configx" ) var serveControls = `## Configuration Ory Hydra can be configured using environment variables as well as a configuration file. For more information on configuration options, open the configuration documentation: >> https://www.ory.sh/hydra/docs/reference/configuration << ` // serveCmd represents the host command func NewServeCmd() *cobra.Command { cmd := &cobra.Command{ Use: "serve", Short: "Parent command for starting public and administrative HTTP/2 APIs", Long: `Ory Hydra exposes two ports, a public and an administrative port. The public port is responsible for handling requests from the public internet, such as the OAuth 2.0 Authorize and Token URLs. The administrative port handles administrative requests like creating OAuth 2.0 Clients, managing JSON Web Keys, and managing User Login and Consent sessions. It is recommended to run "hydra serve all". If you need granular control over CORS settings or similar, you may want to run "hydra serve admin" and "hydra serve public" separately. To learn more about each individual command, run: - hydra help serve all - hydra help serve admin - hydra help serve public All sub-commands share command line flags and configuration options. ` + serveControls, } configx.RegisterFlags(cmd.PersistentFlags()) cmd.PersistentFlags().Bool("dev", false, "Disables critical security checks to improve local development experience. Do not use in production.") cmd.PersistentFlags().Bool("sqa-opt-out", false, "Disable anonymized telemetry reports - for more information please visit https://www.ory.sh/docs/ecosystem/sqa") return cmd }
Go
hydra/cmd/serve_admin.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" ) // adminCmd represents the admin command func NewServeAdminCmd(slOpts []servicelocatorx.Option, dOpts []driver.OptionsModifier, cOpts []configx.OptionModifier) *cobra.Command { return &cobra.Command{ Use: "admin", Short: "Serves Administrative HTTP/2 APIs", Long: `This command opens one port and listens to HTTP/2 API requests. The exposed API handles administrative requests like managing OAuth 2.0 Clients, JSON Web Keys, login and consent sessions, and others. This command is configurable using the same options available to "serve public" and "serve all". It is generally recommended to use this command only if you require granular control over the administrative and public APIs. For example, you might want to run different TLS certificates or CORS settings on the public and administrative API. This command does not work with the "memory" database. Both services (administrative, public) MUST use the same database connection to be able to synchronize. ` + serveControls, RunE: server.RunServeAdmin(slOpts, dOpts, cOpts), } }