Upgrade to Spring Javaformat 0.38.
Closes gh-781
This commit is contained in:
355
etc/ide/org.eclipse.core.jdt.prefs
Normal file
355
etc/ide/org.eclipse.core.jdt.prefs
Normal file
@@ -0,0 +1,355 @@
|
||||
core.formatter.align_assignment_statements_on_columns=false
|
||||
core.formatter.align_fields_grouping_blank_lines=2147483647
|
||||
core.formatter.align_type_members_on_columns=false
|
||||
core.formatter.align_variable_declarations_on_columns=false
|
||||
core.formatter.align_with_spaces=false
|
||||
core.formatter.alignment_for_additive_operator=16
|
||||
core.formatter.alignment_for_arguments_in_allocation_expression=16
|
||||
core.formatter.alignment_for_arguments_in_annotation=16
|
||||
core.formatter.alignment_for_arguments_in_enum_constant=16
|
||||
core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
|
||||
core.formatter.alignment_for_arguments_in_method_invocation=16
|
||||
core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
|
||||
core.formatter.alignment_for_assignment=0
|
||||
core.formatter.alignment_for_binary_expression=16
|
||||
core.formatter.alignment_for_bitwise_operator=16
|
||||
core.formatter.alignment_for_compact_if=16
|
||||
core.formatter.alignment_for_compact_loops=16
|
||||
core.formatter.alignment_for_conditional_expression=16
|
||||
core.formatter.alignment_for_conditional_expression_chain=0
|
||||
core.formatter.alignment_for_enum_constants=16
|
||||
core.formatter.alignment_for_expressions_in_array_initializer=16
|
||||
core.formatter.alignment_for_expressions_in_for_loop_header=0
|
||||
core.formatter.alignment_for_logical_operator=16
|
||||
core.formatter.alignment_for_method_declaration=0
|
||||
core.formatter.alignment_for_module_statements=16
|
||||
core.formatter.alignment_for_multiple_fields=16
|
||||
core.formatter.alignment_for_multiplicative_operator=16
|
||||
core.formatter.alignment_for_parameterized_type_references=0
|
||||
core.formatter.alignment_for_parameters_in_constructor_declaration=16
|
||||
core.formatter.alignment_for_parameters_in_method_declaration=16
|
||||
core.formatter.alignment_for_relational_operator=0
|
||||
core.formatter.alignment_for_resources_in_try=80
|
||||
core.formatter.alignment_for_selector_in_method_invocation=84
|
||||
core.formatter.alignment_for_shift_operator=0
|
||||
core.formatter.alignment_for_string_concatenation=16
|
||||
core.formatter.alignment_for_superclass_in_type_declaration=16
|
||||
core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
|
||||
core.formatter.alignment_for_superinterfaces_in_type_declaration=16
|
||||
core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
|
||||
core.formatter.alignment_for_throws_clause_in_method_declaration=16
|
||||
core.formatter.alignment_for_type_arguments=0
|
||||
core.formatter.alignment_for_type_parameters=0
|
||||
core.formatter.alignment_for_union_type_in_multicatch=16
|
||||
core.formatter.align_selector_in_method_invocation_on_expression_first_line=true
|
||||
core.formatter.blank_lines_after_imports=1
|
||||
core.formatter.blank_lines_after_package=1
|
||||
core.formatter.blank_lines_before_field=0
|
||||
core.formatter.blank_lines_before_first_class_body_declaration=0
|
||||
core.formatter.blank_lines_before_imports=1
|
||||
core.formatter.blank_lines_before_member_type=1
|
||||
core.formatter.blank_lines_before_method=1
|
||||
core.formatter.blank_lines_before_new_chunk=1
|
||||
core.formatter.blank_lines_before_package=0
|
||||
core.formatter.blank_lines_between_import_groups=1
|
||||
core.formatter.blank_lines_between_type_declarations=1
|
||||
core.formatter.brace_position_for_annotation_type_declaration=end_of_line
|
||||
core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
|
||||
core.formatter.brace_position_for_array_initializer=end_of_line
|
||||
core.formatter.brace_position_for_block=end_of_line
|
||||
core.formatter.brace_position_for_block_in_case=end_of_line
|
||||
core.formatter.brace_position_for_constructor_declaration=end_of_line
|
||||
core.formatter.brace_position_for_enum_constant=end_of_line
|
||||
core.formatter.brace_position_for_enum_declaration=end_of_line
|
||||
core.formatter.brace_position_for_lambda_body=end_of_line
|
||||
core.formatter.brace_position_for_method_declaration=end_of_line
|
||||
core.formatter.brace_position_for_switch=end_of_line
|
||||
core.formatter.brace_position_for_type_declaration=end_of_line
|
||||
core.formatter.comment.align_tags_descriptions_grouped=false
|
||||
core.formatter.comment.align_tags_names_descriptions=false
|
||||
core.formatter.comment.clear_blank_lines_in_block_comment=false
|
||||
core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
|
||||
core.formatter.comment.count_line_length_from_starting_position=false
|
||||
core.formatter.comment.format_block_comments=true
|
||||
core.formatter.comment.format_header=false
|
||||
core.formatter.comment.format_html=true
|
||||
core.formatter.comment.format_javadoc_comments=true
|
||||
core.formatter.comment.format_line_comments=true
|
||||
core.formatter.comment.format_source_code=false
|
||||
core.formatter.comment.indent_parameter_description=false
|
||||
core.formatter.comment.indent_root_tags=false
|
||||
core.formatter.comment.indent_tag_description=false
|
||||
core.formatter.comment.insert_new_line_before_root_tags=do not insert
|
||||
core.formatter.comment.insert_new_line_for_parameter=do not insert
|
||||
core.formatter.comment.line_length=90
|
||||
core.formatter.comment.new_lines_at_block_boundaries=true
|
||||
core.formatter.comment.new_lines_at_javadoc_boundaries=true
|
||||
core.formatter.comment.preserve_white_space_between_code_and_line_comments=false
|
||||
core.formatter.compact_else_if=true
|
||||
core.formatter.continuation_indentation=2
|
||||
core.formatter.continuation_indentation_for_array_initializer=2
|
||||
core.formatter.disabling_tag=@formatter\:off
|
||||
core.formatter.enabling_tag=@formatter\:on
|
||||
core.formatter.format_guardian_clause_on_one_line=false
|
||||
core.formatter.format_line_comment_starting_on_first_column=true
|
||||
core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
|
||||
core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
|
||||
core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
|
||||
core.formatter.indent_body_declarations_compare_to_type_header=true
|
||||
core.formatter.indent_breaks_compare_to_cases=true
|
||||
core.formatter.indent_empty_lines=false
|
||||
core.formatter.indent_statements_compare_to_block=true
|
||||
core.formatter.indent_statements_compare_to_body=true
|
||||
core.formatter.indent_switchstatements_compare_to_cases=true
|
||||
core.formatter.indent_switchstatements_compare_to_switch=true
|
||||
core.formatter.indentation.size=4
|
||||
core.formatter.insert_new_line_after_annotation_on_enum_constant=insert
|
||||
core.formatter.insert_new_line_after_annotation_on_field=insert
|
||||
core.formatter.insert_new_line_after_annotation_on_local_variable=insert
|
||||
core.formatter.insert_new_line_after_annotation_on_method=insert
|
||||
core.formatter.insert_new_line_after_annotation_on_package=insert
|
||||
core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
|
||||
core.formatter.insert_new_line_after_annotation_on_type=insert
|
||||
core.formatter.insert_new_line_after_label=do not insert
|
||||
core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
|
||||
core.formatter.insert_new_line_after_type_annotation=do not insert
|
||||
core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
|
||||
core.formatter.insert_new_line_before_catch_in_try_statement=insert
|
||||
core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
|
||||
core.formatter.insert_new_line_before_else_in_if_statement=insert
|
||||
core.formatter.insert_new_line_before_finally_in_try_statement=insert
|
||||
core.formatter.insert_new_line_before_while_in_do_statement=insert
|
||||
core.formatter.insert_new_line_in_empty_annotation_declaration=insert
|
||||
core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
|
||||
core.formatter.insert_new_line_in_empty_block=insert
|
||||
core.formatter.insert_new_line_in_empty_enum_constant=insert
|
||||
core.formatter.insert_new_line_in_empty_enum_declaration=insert
|
||||
core.formatter.insert_new_line_in_empty_method_body=insert
|
||||
core.formatter.insert_new_line_in_empty_type_declaration=insert
|
||||
core.formatter.insert_space_after_additive_operator=insert
|
||||
core.formatter.insert_space_after_and_in_type_parameter=insert
|
||||
core.formatter.insert_space_after_assignment_operator=insert
|
||||
core.formatter.insert_space_after_at_in_annotation=do not insert
|
||||
core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
|
||||
core.formatter.insert_space_after_binary_operator=insert
|
||||
core.formatter.insert_space_after_bitwise_operator=insert
|
||||
core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert
|
||||
core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
|
||||
core.formatter.insert_space_after_closing_brace_in_block=insert
|
||||
core.formatter.insert_space_after_closing_paren_in_cast=insert
|
||||
core.formatter.insert_space_after_colon_in_assert=insert
|
||||
core.formatter.insert_space_after_colon_in_case=insert
|
||||
core.formatter.insert_space_after_colon_in_conditional=insert
|
||||
core.formatter.insert_space_after_colon_in_for=insert
|
||||
core.formatter.insert_space_after_colon_in_labeled_statement=insert
|
||||
core.formatter.insert_space_after_comma_in_allocation_expression=insert
|
||||
core.formatter.insert_space_after_comma_in_annotation=insert
|
||||
core.formatter.insert_space_after_comma_in_array_initializer=insert
|
||||
core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
|
||||
core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
|
||||
core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
|
||||
core.formatter.insert_space_after_comma_in_enum_declarations=insert
|
||||
core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
|
||||
core.formatter.insert_space_after_comma_in_for_increments=insert
|
||||
core.formatter.insert_space_after_comma_in_for_inits=insert
|
||||
core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
|
||||
core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
|
||||
core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
|
||||
core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
|
||||
core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
|
||||
core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
|
||||
core.formatter.insert_space_after_comma_in_superinterfaces=insert
|
||||
core.formatter.insert_space_after_comma_in_type_arguments=insert
|
||||
core.formatter.insert_space_after_comma_in_type_parameters=insert
|
||||
core.formatter.insert_space_after_ellipsis=insert
|
||||
core.formatter.insert_space_after_lambda_arrow=insert
|
||||
core.formatter.insert_space_after_logical_operator=insert
|
||||
core.formatter.insert_space_after_multiplicative_operator=insert
|
||||
core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
|
||||
core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
|
||||
core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
|
||||
core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
|
||||
core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
|
||||
core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_cast=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_catch=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_for=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_if=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_switch=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_try=do not insert
|
||||
core.formatter.insert_space_after_opening_paren_in_while=do not insert
|
||||
core.formatter.insert_space_after_postfix_operator=do not insert
|
||||
core.formatter.insert_space_after_prefix_operator=do not insert
|
||||
core.formatter.insert_space_after_question_in_conditional=insert
|
||||
core.formatter.insert_space_after_question_in_wildcard=do not insert
|
||||
core.formatter.insert_space_after_relational_operator=insert
|
||||
core.formatter.insert_space_after_semicolon_in_for=insert
|
||||
core.formatter.insert_space_after_semicolon_in_try_resources=insert
|
||||
core.formatter.insert_space_after_shift_operator=insert
|
||||
core.formatter.insert_space_after_string_concatenation=insert
|
||||
core.formatter.insert_space_after_unary_operator=do not insert
|
||||
core.formatter.insert_space_before_additive_operator=insert
|
||||
core.formatter.insert_space_before_and_in_type_parameter=insert
|
||||
core.formatter.insert_space_before_assignment_operator=insert
|
||||
core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
|
||||
core.formatter.insert_space_before_binary_operator=insert
|
||||
core.formatter.insert_space_before_bitwise_operator=insert
|
||||
core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
|
||||
core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
|
||||
core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
|
||||
core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
|
||||
core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
|
||||
core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_cast=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_catch=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_for=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_if=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_switch=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_try=do not insert
|
||||
core.formatter.insert_space_before_closing_paren_in_while=do not insert
|
||||
core.formatter.insert_space_before_colon_in_assert=insert
|
||||
core.formatter.insert_space_before_colon_in_case=do not insert
|
||||
core.formatter.insert_space_before_colon_in_conditional=insert
|
||||
core.formatter.insert_space_before_colon_in_default=do not insert
|
||||
core.formatter.insert_space_before_colon_in_for=insert
|
||||
core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
|
||||
core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
|
||||
core.formatter.insert_space_before_comma_in_annotation=do not insert
|
||||
core.formatter.insert_space_before_comma_in_array_initializer=do not insert
|
||||
core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
|
||||
core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
|
||||
core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
|
||||
core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
|
||||
core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
|
||||
core.formatter.insert_space_before_comma_in_for_increments=do not insert
|
||||
core.formatter.insert_space_before_comma_in_for_inits=do not insert
|
||||
core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
|
||||
core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
|
||||
core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
|
||||
core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
|
||||
core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
|
||||
core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
|
||||
core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
|
||||
core.formatter.insert_space_before_comma_in_type_arguments=do not insert
|
||||
core.formatter.insert_space_before_comma_in_type_parameters=do not insert
|
||||
core.formatter.insert_space_before_ellipsis=do not insert
|
||||
core.formatter.insert_space_before_lambda_arrow=insert
|
||||
core.formatter.insert_space_before_logical_operator=insert
|
||||
core.formatter.insert_space_before_multiplicative_operator=insert
|
||||
core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
|
||||
core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
|
||||
core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
|
||||
core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_block=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_switch=insert
|
||||
core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
|
||||
core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
|
||||
core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
|
||||
core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_catch=insert
|
||||
core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_for=insert
|
||||
core.formatter.insert_space_before_opening_paren_in_if=insert
|
||||
core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
|
||||
core.formatter.insert_space_before_opening_paren_in_switch=insert
|
||||
core.formatter.insert_space_before_opening_paren_in_synchronized=insert
|
||||
core.formatter.insert_space_before_opening_paren_in_try=insert
|
||||
core.formatter.insert_space_before_opening_paren_in_while=insert
|
||||
core.formatter.insert_space_before_parenthesized_expression_in_return=insert
|
||||
core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
|
||||
core.formatter.insert_space_before_postfix_operator=do not insert
|
||||
core.formatter.insert_space_before_prefix_operator=do not insert
|
||||
core.formatter.insert_space_before_question_in_conditional=insert
|
||||
core.formatter.insert_space_before_question_in_wildcard=do not insert
|
||||
core.formatter.insert_space_before_relational_operator=insert
|
||||
core.formatter.insert_space_before_semicolon=do not insert
|
||||
core.formatter.insert_space_before_semicolon_in_for=do not insert
|
||||
core.formatter.insert_space_before_semicolon_in_try_resources=do not insert
|
||||
core.formatter.insert_space_before_shift_operator=insert
|
||||
core.formatter.insert_space_before_string_concatenation=insert
|
||||
core.formatter.insert_space_before_unary_operator=do not insert
|
||||
core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
|
||||
core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
|
||||
core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
|
||||
core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
|
||||
core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
|
||||
core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
|
||||
core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
|
||||
core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
|
||||
core.formatter.join_lines_in_comments=true
|
||||
core.formatter.join_wrapped_lines=true
|
||||
core.formatter.keep_annotation_declaration_on_one_line=one_line_never
|
||||
core.formatter.keep_anonymous_type_declaration_on_one_line=one_line_never
|
||||
core.formatter.keep_code_block_on_one_line=one_line_never
|
||||
core.formatter.keep_else_statement_on_same_line=false
|
||||
core.formatter.keep_empty_array_initializer_on_one_line=false
|
||||
core.formatter.keep_enum_constant_declaration_on_one_line=one_line_never
|
||||
core.formatter.keep_enum_declaration_on_one_line=one_line_never
|
||||
core.formatter.keep_if_then_body_block_on_one_line=one_line_never
|
||||
core.formatter.keep_imple_if_on_one_line=false
|
||||
core.formatter.keep_lambda_body_block_on_one_line=one_line_never
|
||||
core.formatter.keep_loop_body_block_on_one_line=one_line_never
|
||||
core.formatter.keep_method_body_on_one_line=one_line_never
|
||||
core.formatter.keep_simple_do_while_body_on_same_line=false
|
||||
core.formatter.keep_simple_for_body_on_same_line=false
|
||||
core.formatter.keep_simple_getter_setter_on_one_line=false
|
||||
core.formatter.keep_simple_while_body_on_same_line=false
|
||||
core.formatter.keep_then_statement_on_same_line=false
|
||||
core.formatter.keep_type_declaration_on_one_line=one_line_never
|
||||
core.formatter.lineSplit=120
|
||||
core.formatter.never_indent_block_comments_on_first_column=false
|
||||
core.formatter.never_indent_line_comments_on_first_column=false
|
||||
core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
|
||||
core.formatter.number_of_empty_lines_to_preserve=1
|
||||
core.formatter.parentheses_positions_in_annotation=common_lines
|
||||
core.formatter.parentheses_positions_in_catch_clause=common_lines
|
||||
core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines
|
||||
core.formatter.parentheses_positions_in_for_statment=common_lines
|
||||
core.formatter.parentheses_positions_in_if_while_statement=common_lines
|
||||
core.formatter.parentheses_positions_in_lambda_declaration=common_lines
|
||||
core.formatter.parentheses_positions_in_method_delcaration=common_lines
|
||||
core.formatter.parentheses_positions_in_method_invocation=common_lines
|
||||
core.formatter.parentheses_positions_in_switch_statement=common_lines
|
||||
core.formatter.parentheses_positions_in_try_clause=common_lines
|
||||
core.formatter.put_empty_statement_on_new_line=true
|
||||
core.formatter.tabulation.char=tab
|
||||
core.formatter.tabulation.size=4
|
||||
core.formatter.use_on_off_tags=true
|
||||
core.formatter.use_tabs_only_for_leading_indentations=false
|
||||
core.formatter.wrap_before_additive_operator=true
|
||||
core.formatter.wrap_before_assignment_operator=false
|
||||
core.formatter.wrap_before_binary_operator=true
|
||||
core.formatter.wrap_before_bitwise_operator=true
|
||||
core.formatter.wrap_before_conditional_operator=true
|
||||
core.formatter.wrap_before_logical_operator=true
|
||||
core.formatter.wrap_before_multiplicative_operator=true
|
||||
core.formatter.wrap_before_or_operator_multicatch=true
|
||||
core.formatter.wrap_before_relational_operator=true
|
||||
core.formatter.wrap_before_shift_operator=true
|
||||
core.formatter.wrap_before_string_concatenation=true
|
||||
core.formatter.wrap_outer_expressions_when_nested=true
|
||||
2
pom.xml
2
pom.xml
@@ -333,7 +333,7 @@
|
||||
<plugin>
|
||||
<groupId>io.spring.javaformat</groupId>
|
||||
<artifactId>spring-javaformat-maven-plugin</artifactId>
|
||||
<version>0.0.29</version>
|
||||
<version>0.0.38</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>validate</phase>
|
||||
|
||||
@@ -76,8 +76,9 @@ class VaultPropertySourceRegistrar
|
||||
beanFactory.getBeansOfType(org.springframework.vault.core.env.VaultPropertySource.class).values(),
|
||||
propertySources);
|
||||
|
||||
registerPropertySources(beanFactory
|
||||
.getBeansOfType(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class).values(),
|
||||
registerPropertySources(
|
||||
beanFactory.getBeansOfType(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class)
|
||||
.values(),
|
||||
propertySources);
|
||||
}
|
||||
|
||||
@@ -102,9 +103,9 @@ class VaultPropertySourceRegistrar
|
||||
|
||||
if (!registry.isBeanNameInUse("VaultPropertySourceRegistrar")) {
|
||||
registry.registerBeanDefinition("VaultPropertySourceRegistrar", BeanDefinitionBuilder //
|
||||
.rootBeanDefinition(VaultPropertySourceRegistrar.class) //
|
||||
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) //
|
||||
.getBeanDefinition());
|
||||
.rootBeanDefinition(VaultPropertySourceRegistrar.class) //
|
||||
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) //
|
||||
.getBeanDefinition());
|
||||
}
|
||||
|
||||
Set<AnnotationAttributes> propertySources = attributesForRepeatable(annotationMetadata,
|
||||
@@ -163,7 +164,7 @@ class VaultPropertySourceRegistrar
|
||||
|
||||
if (isRenewable(renewal)) {
|
||||
builder = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class);
|
||||
.rootBeanDefinition(org.springframework.vault.core.env.LeaseAwareVaultPropertySource.class);
|
||||
|
||||
RequestedSecret requestedSecret = renewal == Renewal.ROTATE ? RequestedSecret.rotating(propertyPath)
|
||||
: RequestedSecret.renewable(propertyPath);
|
||||
@@ -174,7 +175,7 @@ class VaultPropertySourceRegistrar
|
||||
}
|
||||
else {
|
||||
builder = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(org.springframework.vault.core.env.VaultPropertySource.class);
|
||||
.rootBeanDefinition(org.springframework.vault.core.env.VaultPropertySource.class);
|
||||
|
||||
builder.addConstructorArgValue(propertyPath);
|
||||
builder.addConstructorArgReference(ref);
|
||||
|
||||
@@ -69,24 +69,25 @@ class VaultRuntimeHints implements RuntimeHintsRegistrar {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
Stream.of("org.springframework.vault.core.VaultSysTemplate$GetMounts$VaultMountsResponse",
|
||||
"org.springframework.vault.core.VaultVersionedKeyValueTemplate$VersionedResponse",
|
||||
"org.springframework.vault.core.ReactiveVaultTemplate$VaultListResponse",
|
||||
"org.springframework.vault.core.VaultListResponse",
|
||||
Stream
|
||||
.of("org.springframework.vault.core.VaultSysTemplate$GetMounts$VaultMountsResponse",
|
||||
"org.springframework.vault.core.VaultVersionedKeyValueTemplate$VersionedResponse",
|
||||
"org.springframework.vault.core.ReactiveVaultTemplate$VaultListResponse",
|
||||
"org.springframework.vault.core.VaultListResponse",
|
||||
|
||||
"org.springframework.vault.core.VaultTransitTemplate$RawTransitKeyImpl",
|
||||
"org.springframework.vault.core.VaultTransitTemplate$VaultTransitKeyImpl",
|
||||
"org.springframework.vault.core.VaultTransitTemplate$RawTransitKeyImpl",
|
||||
"org.springframework.vault.core.VaultTransitTemplate$VaultTransitKeyImpl",
|
||||
|
||||
"org.springframework.vault.core.VaultSysTemplate$GetMounts",
|
||||
"org.springframework.vault.core.VaultSysTemplate$GetUnsealStatus",
|
||||
"org.springframework.vault.core.VaultSysTemplate$Health",
|
||||
"org.springframework.vault.core.VaultSysTemplate$Seal",
|
||||
"org.springframework.vault.core.VaultSysTemplate$VaultHealthImpl",
|
||||
"org.springframework.vault.core.VaultSysTemplate$VaultInitializationResponseImpl",
|
||||
"org.springframework.vault.core.VaultSysTemplate$VaultUnsealStatusImpl",
|
||||
"org.springframework.vault.core.VaultSysTemplate$GetMounts",
|
||||
"org.springframework.vault.core.VaultSysTemplate$GetUnsealStatus",
|
||||
"org.springframework.vault.core.VaultSysTemplate$Health",
|
||||
"org.springframework.vault.core.VaultSysTemplate$Seal",
|
||||
"org.springframework.vault.core.VaultSysTemplate$VaultHealthImpl",
|
||||
"org.springframework.vault.core.VaultSysTemplate$VaultInitializationResponseImpl",
|
||||
"org.springframework.vault.core.VaultSysTemplate$VaultUnsealStatusImpl",
|
||||
|
||||
"org.springframework.vault.core.VaultVersionedKeyValueTemplate$VersionedResponse")
|
||||
.forEach(cls -> reflection.registerType(TypeReference.of(cls), dataObjectCategories));
|
||||
"org.springframework.vault.core.VaultVersionedKeyValueTemplate$VersionedResponse")
|
||||
.forEach(cls -> reflection.registerType(TypeReference.of(cls), dataObjectCategories));
|
||||
|
||||
reflection.registerTypeIfPresent(classLoader, "com.google.api.client.json.jackson2.JacksonFactory",
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
|
||||
|
||||
@@ -75,8 +75,8 @@ public class AppIdAuthentication implements ClientAuthentication, Authentication
|
||||
Assert.notNull(options, "AppIdAuthenticationOptions must not be null");
|
||||
|
||||
return AuthenticationSteps
|
||||
.fromSupplier(() -> getAppIdLogin(options.getAppId(), options.getUserIdMechanism().createUserId())) //
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
.fromSupplier(() -> getAppIdLogin(options.getAppId(), options.getUserIdMechanism().createUserId())) //
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,7 +96,7 @@ public class AppIdAuthentication implements ClientAuthentication, Authentication
|
||||
|
||||
try {
|
||||
VaultResponse response = this.restOperations
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
|
||||
Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");
|
||||
|
||||
|
||||
@@ -126,13 +126,13 @@ public class AppRoleAuthentication implements ClientAuthentication, Authenticati
|
||||
HttpHeaders headers = createHttpHeaders(((Pull) roleId).getInitialToken());
|
||||
|
||||
return AuthenticationSteps
|
||||
.fromHttpRequest(get(getRoleIdIdPath(options)).with(headers).as(VaultResponse.class))
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id"));
|
||||
.fromHttpRequest(get(getRoleIdIdPath(options)).with(headers).as(VaultResponse.class))
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id"));
|
||||
}
|
||||
|
||||
if (roleId instanceof Wrapped) {
|
||||
return unwrapResponse(options.getUnwrappingEndpoints(), ((Wrapped) roleId).getInitialToken())
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id"));
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id"));
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unknown RoleId configuration: " + roleId);
|
||||
@@ -148,14 +148,14 @@ public class AppRoleAuthentication implements ClientAuthentication, Authenticati
|
||||
HttpHeaders headers = createHttpHeaders(((Pull) secretId).getInitialToken());
|
||||
|
||||
return AuthenticationSteps
|
||||
.fromHttpRequest(post(getSecretIdPath(options)).with(headers).as(VaultResponse.class))
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id"));
|
||||
.fromHttpRequest(post(getSecretIdPath(options)).with(headers).as(VaultResponse.class))
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id"));
|
||||
}
|
||||
|
||||
if (secretId instanceof Wrapped) {
|
||||
|
||||
return unwrapResponse(options.getUnwrappingEndpoints(), ((Wrapped) secretId).getInitialToken())
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id"));
|
||||
.map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id"));
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unknown SecretId configuration: " + secretId);
|
||||
@@ -165,9 +165,10 @@ public class AppRoleAuthentication implements ClientAuthentication, Authenticati
|
||||
private static Node<VaultResponse> unwrapResponse(UnwrappingEndpoints unwrappingEndpoints, VaultToken token) {
|
||||
|
||||
return AuthenticationSteps
|
||||
.fromHttpRequest(method(unwrappingEndpoints.getUnwrapRequestMethod(), unwrappingEndpoints.getPath())
|
||||
.with(createHttpHeaders(token)).as(VaultResponse.class))
|
||||
.map(unwrappingEndpoints::unwrap);
|
||||
.fromHttpRequest(method(unwrappingEndpoints.getUnwrapRequestMethod(), unwrappingEndpoints.getPath())
|
||||
.with(createHttpHeaders(token))
|
||||
.as(VaultResponse.class))
|
||||
.map(unwrappingEndpoints::unwrap);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -136,7 +136,7 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier {
|
||||
|
||||
if (o instanceof ZipStep) {
|
||||
state = state.zipWith(doZipStep((ZipStep<Object, Object>) o))
|
||||
.map(it -> Pair.of(it.getT1(), it.getT2()));
|
||||
.map(it -> Pair.of(it.getT1(), it.getT2()));
|
||||
}
|
||||
|
||||
if (o instanceof OnNextStep) {
|
||||
@@ -166,8 +166,8 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier {
|
||||
RequestBodySpec spec;
|
||||
if (definition.getUri() == null) {
|
||||
|
||||
spec = this.webClient.method(definition.getMethod()).uri(definition.getUriTemplate(),
|
||||
definition.getUrlVariables());
|
||||
spec = this.webClient.method(definition.getMethod())
|
||||
.uri(definition.getUriTemplate(), definition.getUrlVariables());
|
||||
}
|
||||
else {
|
||||
spec = this.webClient.method(definition.getMethod()).uri(definition.getUri());
|
||||
@@ -224,14 +224,13 @@ public class AuthenticationStepsOperator implements VaultTokenSupplier {
|
||||
ResourceCredentialSupplier resourceSupplier = (ResourceCredentialSupplier) supplier;
|
||||
|
||||
return DataBufferUtils.join(DataBufferUtils.read(resourceSupplier.getResource(), this.factory, 4096))
|
||||
.map(dataBuffer -> {
|
||||
String result = dataBuffer.toString(ResourceCredentialSupplier.CHARSET);
|
||||
DataBufferUtils.release(dataBuffer);
|
||||
return (Object) result;
|
||||
}).onErrorMap(IOException.class,
|
||||
e -> new VaultException(
|
||||
String.format("Credential retrieval from %s failed", resourceSupplier.getResource()),
|
||||
e));
|
||||
.map(dataBuffer -> {
|
||||
String result = dataBuffer.toString(ResourceCredentialSupplier.CHARSET);
|
||||
DataBufferUtils.release(dataBuffer);
|
||||
return (Object) result;
|
||||
})
|
||||
.onErrorMap(IOException.class, e -> new VaultException(
|
||||
String.format("Credential retrieval from %s failed", resourceSupplier.getResource()), e));
|
||||
}
|
||||
|
||||
enum Undefinded {
|
||||
|
||||
@@ -108,26 +108,27 @@ public class AwsEc2Authentication implements ClientAuthentication, Authenticatio
|
||||
AtomicReference<char[]> nonce, Supplier<char[]> nonceSupplier) {
|
||||
|
||||
return AuthenticationSteps
|
||||
.fromHttpRequest(HttpRequestBuilder.get(options.getIdentityDocumentUri().toString()).as(String.class)) //
|
||||
.map(pkcs7 -> pkcs7.replaceAll("\\r", "")) //
|
||||
.map(pkcs7 -> pkcs7.replaceAll("\\n", "")) //
|
||||
.map(pkcs7 -> {
|
||||
.fromHttpRequest(HttpRequestBuilder.get(options.getIdentityDocumentUri().toString()).as(String.class)) //
|
||||
.map(pkcs7 -> pkcs7.replaceAll("\\r", "")) //
|
||||
.map(pkcs7 -> pkcs7.replaceAll("\\n", "")) //
|
||||
.map(pkcs7 -> {
|
||||
|
||||
Map<String, String> login = new HashMap<>();
|
||||
Map<String, String> login = new HashMap<>();
|
||||
|
||||
if (StringUtils.hasText(options.getRole())) {
|
||||
login.put("role", options.getRole());
|
||||
}
|
||||
if (StringUtils.hasText(options.getRole())) {
|
||||
login.put("role", options.getRole());
|
||||
}
|
||||
|
||||
if (Objects.equals(nonce.get(), EMPTY)) {
|
||||
nonce.compareAndSet(EMPTY, nonceSupplier.get());
|
||||
}
|
||||
if (Objects.equals(nonce.get(), EMPTY)) {
|
||||
nonce.compareAndSet(EMPTY, nonceSupplier.get());
|
||||
}
|
||||
|
||||
login.put("nonce", new String(nonce.get()));
|
||||
login.put("pkcs7", pkcs7);
|
||||
login.put("nonce", new String(nonce.get()));
|
||||
login.put("pkcs7", pkcs7);
|
||||
|
||||
return login;
|
||||
}).login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
return login;
|
||||
})
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -148,7 +149,7 @@ public class AwsEc2Authentication implements ClientAuthentication, Authenticatio
|
||||
try {
|
||||
|
||||
VaultResponse response = this.vaultRestOperations
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
|
||||
Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ import org.springframework.util.Assert;
|
||||
public class AwsEc2AuthenticationOptions {
|
||||
|
||||
public static final URI DEFAULT_PKCS7_IDENTITY_DOCUMENT_URI = URI
|
||||
.create("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7");
|
||||
.create("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7");
|
||||
|
||||
public static final String DEFAULT_AWS_AUTHENTICATION_PATH = "aws-ec2";
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ public class AwsIamAuthentication implements ClientAuthentication, Authenticatio
|
||||
AwsCredentials credentials, Region region) {
|
||||
|
||||
return AuthenticationSteps.fromSupplier(() -> createRequestBody(options, credentials, region)) //
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -147,7 +147,7 @@ public class AwsIamAuthentication implements ClientAuthentication, Authenticatio
|
||||
try {
|
||||
|
||||
VaultResponse response = this.vaultRestOperations
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
|
||||
Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");
|
||||
|
||||
@@ -214,13 +214,18 @@ public class AwsIamAuthentication implements ClientAuthentication, Authenticatio
|
||||
Map<String, List<String>> headers = createIamRequestHeaders(options);
|
||||
|
||||
SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder()
|
||||
.contentStreamProvider(() -> new ByteArrayInputStream(REQUEST_BODY.getBytes())).headers(headers)
|
||||
.method(SdkHttpMethod.POST).uri(options.getEndpointUri());
|
||||
.contentStreamProvider(() -> new ByteArrayInputStream(REQUEST_BODY.getBytes()))
|
||||
.headers(headers)
|
||||
.method(SdkHttpMethod.POST)
|
||||
.uri(options.getEndpointUri());
|
||||
SdkHttpFullRequest request = builder.build();
|
||||
|
||||
Aws4Signer signer = Aws4Signer.create();
|
||||
Aws4SignerParams signerParams = Aws4SignerParams.builder().awsCredentials(credentials).signingName("sts")
|
||||
.signingRegion(region).build();
|
||||
Aws4SignerParams signerParams = Aws4SignerParams.builder()
|
||||
.awsCredentials(credentials)
|
||||
.signingName("sts")
|
||||
.signingRegion(region)
|
||||
.build();
|
||||
SdkHttpFullRequest signedRequest = signer.sign(request, signerParams);
|
||||
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
|
||||
@@ -117,26 +117,27 @@ public class AzureMsiAuthentication implements ClientAuthentication, Authenticat
|
||||
@Nullable AzureVmEnvironment environment) {
|
||||
|
||||
Node<String> msiToken = AuthenticationSteps
|
||||
.fromHttpRequest(HttpRequestBuilder.get(options.getIdentityTokenServiceUri()).with(METADATA_HEADERS)
|
||||
.as(Map.class)) //
|
||||
.map(token -> (String) token.get("access_token"));
|
||||
.fromHttpRequest(
|
||||
HttpRequestBuilder.get(options.getIdentityTokenServiceUri()).with(METADATA_HEADERS).as(Map.class)) //
|
||||
.map(token -> (String) token.get("access_token"));
|
||||
|
||||
Node<AzureVmEnvironment> environmentSteps;
|
||||
|
||||
if (environment == null) {
|
||||
|
||||
environmentSteps = AuthenticationSteps
|
||||
.fromHttpRequest(HttpRequestBuilder.get(options.getInstanceMetadataServiceUri())
|
||||
.with(METADATA_HEADERS).as(Map.class)) //
|
||||
.map(AzureMsiAuthentication::toAzureVmEnvironment);
|
||||
.fromHttpRequest(HttpRequestBuilder.get(options.getInstanceMetadataServiceUri())
|
||||
.with(METADATA_HEADERS)
|
||||
.as(Map.class)) //
|
||||
.map(AzureMsiAuthentication::toAzureVmEnvironment);
|
||||
}
|
||||
else {
|
||||
environmentSteps = AuthenticationSteps.fromValue(environment);
|
||||
}
|
||||
|
||||
return environmentSteps.zipWith(msiToken)
|
||||
.map(tuple -> getAzureLogin(options.getRole(), tuple.getLeft(), tuple.getRight())) //
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
.map(tuple -> getAzureLogin(options.getRole(), tuple.getLeft(), tuple.getRight())) //
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -156,7 +157,7 @@ public class AzureMsiAuthentication implements ClientAuthentication, Authenticat
|
||||
try {
|
||||
|
||||
VaultResponse response = this.vaultRestOperations
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
|
||||
Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");
|
||||
|
||||
@@ -187,7 +188,7 @@ public class AzureMsiAuthentication implements ClientAuthentication, Authenticat
|
||||
private String getAccessToken() {
|
||||
|
||||
ResponseEntity<Map> response = this.azureMetadataRestOperations
|
||||
.exchange(this.options.getIdentityTokenServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.class);
|
||||
.exchange(this.options.getIdentityTokenServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.class);
|
||||
|
||||
return (String) response.getBody().get("access_token");
|
||||
}
|
||||
@@ -202,7 +203,7 @@ public class AzureMsiAuthentication implements ClientAuthentication, Authenticat
|
||||
private AzureVmEnvironment fetchAzureVmEnvironment() {
|
||||
|
||||
ResponseEntity<Map> response = this.azureMetadataRestOperations
|
||||
.exchange(this.options.getInstanceMetadataServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.class);
|
||||
.exchange(this.options.getInstanceMetadataServiceUri(), HttpMethod.GET, METADATA_HEADERS, Map.class);
|
||||
|
||||
return toAzureVmEnvironment(response.getBody());
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public class AzureMsiAuthenticationOptions {
|
||||
public static final String DEFAULT_AZURE_AUTHENTICATION_PATH = "azure";
|
||||
|
||||
public static final URI DEFAULT_INSTANCE_METADATA_SERVICE_URI = URI
|
||||
.create("http://169.254.169.254/metadata/instance?api-version=2017-12-01");
|
||||
.create("http://169.254.169.254/metadata/instance?api-version=2017-12-01");
|
||||
|
||||
public static final URI DEFAULT_IDENTITY_TOKEN_SERVICE_URI = URI.create(
|
||||
"http://169.254.169.254/metadata/identity/oauth2/token?resource=https://vault.hashicorp.com&api-version=2018-02-01");
|
||||
|
||||
@@ -85,7 +85,7 @@ public class ClientCertificateAuthentication implements ClientAuthentication, Au
|
||||
Assert.notNull(options, "ClientCertificateAuthenticationOptions must not be null");
|
||||
|
||||
return AuthenticationSteps
|
||||
.just(post(AuthenticationUtil.getLoginPath(options.getPath())).as(VaultResponse.class));
|
||||
.just(post(AuthenticationUtil.getLoginPath(options.getPath())).as(VaultResponse.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -171,11 +171,11 @@ public class CubbyholeAuthentication implements ClientAuthentication, Authentica
|
||||
HttpEntity<Object> requestEntity = getRequestEntity(options);
|
||||
|
||||
HttpRequest<VaultResponse> initialRequest = method(unwrapMethod, url) //
|
||||
.with(requestEntity) //
|
||||
.as(VaultResponse.class);
|
||||
.with(requestEntity) //
|
||||
.as(VaultResponse.class);
|
||||
|
||||
return AuthenticationSteps.fromHttpRequest(initialRequest) //
|
||||
.login(it -> getToken(options, it, url));
|
||||
.login(it -> getToken(options, it, url));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -283,7 +283,7 @@ public class CubbyholeAuthentication implements ClientAuthentication, Authentica
|
||||
}
|
||||
|
||||
throw new VaultLoginException(String
|
||||
.format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token", url));
|
||||
.format("Cannot retrieve Token from Cubbyhole: Response at %s does not contain an unique token", url));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -104,13 +104,13 @@ public class GcpComputeAuthentication extends GcpJwtAuthenticationSupport
|
||||
String audience = getAudience(options.getRole());
|
||||
|
||||
HttpRequest<String> jwtRequest = get(COMPUTE_METADATA_URL_TEMPLATE, serviceAccount, audience, "full") //
|
||||
.with(getMetadataHttpHeaders()) //
|
||||
.as(String.class);
|
||||
.with(getMetadataHttpHeaders()) //
|
||||
.as(String.class);
|
||||
|
||||
return AuthenticationSteps.fromHttpRequest(jwtRequest)
|
||||
//
|
||||
.map(jwt -> createRequestBody(options.getRole(), jwt))
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
//
|
||||
.map(jwt -> createRequestBody(options.getRole(), jwt))
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -123,7 +123,8 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport implements
|
||||
Map<String, Object> jwtPayload = getJwtPayload(this.options, serviceAccount);
|
||||
|
||||
Iam iam = new Builder(this.httpTransport, GoogleJsonUtil.JSON_FACTORY, this.credential)
|
||||
.setApplicationName("Spring Vault/" + getClass().getName()).build();
|
||||
.setApplicationName("Spring Vault/" + getClass().getName())
|
||||
.build();
|
||||
|
||||
try {
|
||||
|
||||
@@ -131,8 +132,9 @@ public class GcpIamAuthentication extends GcpJwtAuthenticationSupport implements
|
||||
SignJwtRequest request = new SignJwtRequest();
|
||||
request.setPayload(payload);
|
||||
|
||||
SignJwt signJwt = iam.projects().serviceAccounts()
|
||||
.signJwt(String.format("projects/%s/serviceAccounts/%s", projectId, serviceAccount), request);
|
||||
SignJwt signJwt = iam.projects()
|
||||
.serviceAccounts()
|
||||
.signJwt(String.format("projects/%s/serviceAccounts/%s", projectId, serviceAccount), request);
|
||||
|
||||
SignJwtResponse response = signJwt.execute();
|
||||
|
||||
|
||||
@@ -121,8 +121,9 @@ public class GcpIamCredentialsAuthentication extends GcpJwtAuthenticationSupport
|
||||
|
||||
try {
|
||||
IamCredentialsSettings credentialsSettings = IamCredentialsSettings.newBuilder()
|
||||
.setCredentialsProvider(() -> this.credentials)
|
||||
.setTransportChannelProvider(this.transportChannelProvider).build();
|
||||
.setCredentialsProvider(() -> this.credentials)
|
||||
.setTransportChannelProvider(this.transportChannelProvider)
|
||||
.build();
|
||||
try (IamCredentialsClient iamCredentialsClient = IamCredentialsClient.create(credentialsSettings)) {
|
||||
String payload = GoogleJsonUtil.JSON_FACTORY.toString(jwtPayload);
|
||||
ServiceAccountName serviceAccountName = ServiceAccountName.of("-", serviceAccount);
|
||||
|
||||
@@ -76,8 +76,8 @@ public class KubernetesAuthentication implements ClientAuthentication, Authentic
|
||||
Assert.notNull(options, "KubernetesAuthenticationOptions must not be null");
|
||||
|
||||
return AuthenticationSteps.fromSupplier(options.getJwtSupplier())
|
||||
.map(token -> getKubernetesLogin(options.getRole(), token))
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
.map(token -> getKubernetesLogin(options.getRole(), token))
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -87,7 +87,7 @@ public class KubernetesAuthentication implements ClientAuthentication, Authentic
|
||||
|
||||
try {
|
||||
VaultResponse response = this.restOperations
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
|
||||
Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");
|
||||
|
||||
|
||||
@@ -281,7 +281,7 @@ public class LifecycleAwareSessionManager extends LifecycleAwareSessionManagerSu
|
||||
}
|
||||
|
||||
return getToken().map(TokenWrapper::getToken)
|
||||
.orElseThrow(() -> new IllegalStateException("Cannot obtain VaultToken"));
|
||||
.orElseThrow(() -> new IllegalStateException("Cannot obtain VaultToken"));
|
||||
}
|
||||
|
||||
private void doGetSessionToken() {
|
||||
|
||||
@@ -113,9 +113,9 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
|
||||
}
|
||||
|
||||
return networkInterface.map(MacAddressUserId::getRequiredNetworkAddress) //
|
||||
.map(Sha256::toHexString) //
|
||||
.map(Sha256::toSha256) //
|
||||
.orElseThrow(() -> new IllegalStateException("Cannot determine NetworkInterface"));
|
||||
.map(Sha256::toHexString) //
|
||||
.map(Sha256::toSha256) //
|
||||
.orElseThrow(() -> new IllegalStateException("Cannot determine NetworkInterface"));
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
@@ -135,8 +135,8 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
|
||||
private static Optional<NetworkInterface> getNetworkInterface(String hint, List<NetworkInterface> interfaces) {
|
||||
|
||||
return interfaces.stream() //
|
||||
.filter(anInterface -> matchesHint(hint, anInterface)) //
|
||||
.findFirst();
|
||||
.filter(anInterface -> matchesHint(hint, anInterface)) //
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private static boolean matchesHint(String hint, NetworkInterface networkInterface) {
|
||||
@@ -148,9 +148,9 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
|
||||
List<NetworkInterface> interfaces) {
|
||||
|
||||
return interfaces.stream() //
|
||||
.filter(MacAddressUserId::hasNetworkAddress) //
|
||||
.sorted(Comparator.comparingInt(NetworkInterface::getIndex)) //
|
||||
.findFirst();
|
||||
.filter(MacAddressUserId::hasNetworkAddress) //
|
||||
.sorted(Comparator.comparingInt(NetworkInterface::getIndex)) //
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private static Optional<byte[]> getNetworkAddress(NetworkInterface it) {
|
||||
@@ -166,8 +166,8 @@ public class MacAddressUserId implements AppIdUserIdMechanism {
|
||||
private static byte[] getRequiredNetworkAddress(NetworkInterface it) {
|
||||
|
||||
return getNetworkAddress(it) //
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
String.format("Network interface %s has no hardware address", it.getName())));
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
String.format("Network interface %s has no hardware address", it.getName())));
|
||||
}
|
||||
|
||||
private static boolean hasNetworkAddress(NetworkInterface it) {
|
||||
|
||||
@@ -93,10 +93,10 @@ public class PcfAuthentication implements ClientAuthentication, AuthenticationSt
|
||||
AuthenticationSteps.Node<String> cert = AuthenticationSteps.fromSupplier(options.getInstanceCertSupplier());
|
||||
AuthenticationSteps.Node<String> key = AuthenticationSteps.fromSupplier(options.getInstanceKeySupplier());
|
||||
|
||||
return cert
|
||||
.zipWith(key).map(credentials -> getPcfLogin(options.getRole(), options.getClock(),
|
||||
credentials.getLeft(), credentials.getRight()))
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
return cert.zipWith(key)
|
||||
.map(credentials -> getPcfLogin(options.getRole(), options.getClock(), credentials.getLeft(),
|
||||
credentials.getRight()))
|
||||
.login(AuthenticationUtil.getLoginPath(options.getPath()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -107,7 +107,7 @@ public class PcfAuthentication implements ClientAuthentication, AuthenticationSt
|
||||
|
||||
try {
|
||||
VaultResponse response = this.restOperations
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);
|
||||
|
||||
Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");
|
||||
|
||||
|
||||
@@ -182,11 +182,14 @@ public class ReactiveLifecycleAwareSessionManager extends LifecycleAwareSessionM
|
||||
|
||||
return this.webClient.post().uri("auth/token/revoke-self").headers(httpHeaders -> {
|
||||
httpHeaders.addAll(VaultHttpHeaders.from(token));
|
||||
}).retrieve().bodyToMono(String.class)
|
||||
.doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRevocationEvent(token)))
|
||||
.doOnNext(ignore -> dispatch(new AfterLoginTokenRevocationEvent(token)))
|
||||
.onErrorResume(WebClientResponseException.class, e -> onRevokeFailed(token, e))
|
||||
.onErrorResume(Exception.class, e -> onRevokeFailed(token, e)).then();
|
||||
})
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRevocationEvent(token)))
|
||||
.doOnNext(ignore -> dispatch(new AfterLoginTokenRevocationEvent(token)))
|
||||
.onErrorResume(WebClientResponseException.class, e -> onRevokeFailed(token, e))
|
||||
.onErrorResume(Exception.class, e -> onRevokeFailed(token, e))
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<String> onRevokeFailed(VaultToken token, Throwable e) {
|
||||
@@ -255,35 +258,37 @@ public class ReactiveLifecycleAwareSessionManager extends LifecycleAwareSessionM
|
||||
|
||||
private Mono<TokenWrapper> doRenew(TokenWrapper tokenWrapper) {
|
||||
|
||||
Mono<VaultResponse> exchange = this.webClient.post().uri("auth/token/renew-self")
|
||||
.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(tokenWrapper.token))).retrieve()
|
||||
.bodyToMono(VaultResponse.class);
|
||||
Mono<VaultResponse> exchange = this.webClient.post()
|
||||
.uri("auth/token/renew-self")
|
||||
.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(tokenWrapper.token)))
|
||||
.retrieve()
|
||||
.bodyToMono(VaultResponse.class);
|
||||
|
||||
return exchange.doOnSubscribe(ignore -> dispatch(new BeforeLoginTokenRenewedEvent(tokenWrapper.getToken())))
|
||||
.handle((response, sink) -> {
|
||||
.handle((response, sink) -> {
|
||||
|
||||
LoginToken renewed = LoginTokenUtil.from(response.getRequiredAuth());
|
||||
LoginToken renewed = LoginTokenUtil.from(response.getRequiredAuth());
|
||||
|
||||
if (!isExpired(renewed)) {
|
||||
sink.next(new TokenWrapper(renewed, tokenWrapper.revocable));
|
||||
dispatch(new AfterLoginTokenRenewedEvent(renewed));
|
||||
return;
|
||||
}
|
||||
if (!isExpired(renewed)) {
|
||||
sink.next(new TokenWrapper(renewed, tokenWrapper.revocable));
|
||||
dispatch(new AfterLoginTokenRenewedEvent(renewed));
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
|
||||
Duration validTtlThreshold = getRefreshTrigger().getValidTtlThreshold(renewed);
|
||||
this.logger.info(
|
||||
String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.",
|
||||
renewed.getLeaseDuration(), validTtlThreshold));
|
||||
}
|
||||
else {
|
||||
this.logger.info("Token TTL exceeded validity TTL threshold. Dropping token.");
|
||||
}
|
||||
Duration validTtlThreshold = getRefreshTrigger().getValidTtlThreshold(renewed);
|
||||
this.logger
|
||||
.info(String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.",
|
||||
renewed.getLeaseDuration(), validTtlThreshold));
|
||||
}
|
||||
else {
|
||||
this.logger.info("Token TTL exceeded validity TTL threshold. Dropping token.");
|
||||
}
|
||||
|
||||
dropCurrentToken();
|
||||
dispatch(new LoginTokenExpiredEvent(renewed));
|
||||
});
|
||||
dropCurrentToken();
|
||||
dispatch(new LoginTokenExpiredEvent(renewed));
|
||||
});
|
||||
}
|
||||
|
||||
private void dropCurrentToken() {
|
||||
@@ -302,18 +307,20 @@ public class ReactiveLifecycleAwareSessionManager extends LifecycleAwareSessionM
|
||||
|
||||
if (tokenWrapper == EMPTY) {
|
||||
|
||||
Mono<TokenWrapper> obtainToken = this.clientAuthentication.getVaultToken().flatMap(this::doSelfLookup) //
|
||||
.onErrorMap(it -> {
|
||||
dispatch(new LoginFailedEvent(this.clientAuthentication, it));
|
||||
return it;
|
||||
}).doOnNext(it -> {
|
||||
Mono<TokenWrapper> obtainToken = this.clientAuthentication.getVaultToken()
|
||||
.flatMap(this::doSelfLookup) //
|
||||
.onErrorMap(it -> {
|
||||
dispatch(new LoginFailedEvent(this.clientAuthentication, it));
|
||||
return it;
|
||||
})
|
||||
.doOnNext(it -> {
|
||||
|
||||
if (isTokenRenewable(it.getToken())) {
|
||||
scheduleRenewal(it.getToken());
|
||||
}
|
||||
if (isTokenRenewable(it.getToken())) {
|
||||
scheduleRenewal(it.getToken());
|
||||
}
|
||||
|
||||
dispatch(new AfterLoginEvent(it.getToken()));
|
||||
});
|
||||
dispatch(new AfterLoginEvent(it.getToken()));
|
||||
});
|
||||
|
||||
this.token.compareAndSet(tokenWrapper, obtainToken.cache());
|
||||
}
|
||||
@@ -345,13 +352,15 @@ public class ReactiveLifecycleAwareSessionManager extends LifecycleAwareSessionM
|
||||
*/
|
||||
protected boolean isTokenRenewable(VaultToken token) {
|
||||
|
||||
return Optional.of(token).filter(LoginToken.class::isInstance)
|
||||
//
|
||||
.filter(it -> {
|
||||
return Optional.of(token)
|
||||
.filter(LoginToken.class::isInstance)
|
||||
//
|
||||
.filter(it -> {
|
||||
|
||||
LoginToken loginToken = (LoginToken) it;
|
||||
return !loginToken.getLeaseDuration().isZero() && loginToken.isRenewable();
|
||||
}).isPresent();
|
||||
LoginToken loginToken = (LoginToken) it;
|
||||
return !loginToken.getLeaseDuration().isZero() && loginToken.isRenewable();
|
||||
})
|
||||
.isPresent();
|
||||
}
|
||||
|
||||
private void scheduleRenewal(VaultToken token) {
|
||||
@@ -397,15 +406,19 @@ public class ReactiveLifecycleAwareSessionManager extends LifecycleAwareSessionM
|
||||
|
||||
private static Mono<Map<String, Object>> lookupSelf(WebClient webClient, VaultToken token) {
|
||||
|
||||
return webClient.get().uri("auth/token/lookup-self")
|
||||
.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(token))).retrieve()
|
||||
.bodyToMono(VaultResponse.class).map(it -> {
|
||||
return webClient.get()
|
||||
.uri("auth/token/lookup-self")
|
||||
.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(token)))
|
||||
.retrieve()
|
||||
.bodyToMono(VaultResponse.class)
|
||||
.map(it -> {
|
||||
|
||||
Assert.state(it.getData() != null, "Token response is null");
|
||||
return it.getRequiredData();
|
||||
}).onErrorMap(WebClientResponseException.class, e -> {
|
||||
return new VaultTokenLookupException(format("Token self-lookup", e), e);
|
||||
});
|
||||
Assert.state(it.getData() != null, "Token response is null");
|
||||
return it.getRequiredData();
|
||||
})
|
||||
.onErrorMap(WebClientResponseException.class, e -> {
|
||||
return new VaultTokenLookupException(format("Token self-lookup", e), e);
|
||||
});
|
||||
}
|
||||
|
||||
private static String format(String message, RuntimeException e) {
|
||||
|
||||
@@ -73,10 +73,10 @@ public class TokenAuthentication implements ClientAuthentication, Authentication
|
||||
if (selfLookup) {
|
||||
|
||||
HttpRequest<VaultResponse> httpRequest = get("auth/token/lookup-self").with(VaultHttpHeaders.from(token))
|
||||
.as(VaultResponse.class);
|
||||
.as(VaultResponse.class);
|
||||
|
||||
return AuthenticationSteps.fromHttpRequest(httpRequest)
|
||||
.login(response -> LoginTokenUtil.from(token.toCharArray(), response.getRequiredData()));
|
||||
.login(response -> LoginTokenUtil.from(token.toCharArray(), response.getRequiredData()));
|
||||
}
|
||||
|
||||
return AuthenticationSteps.just(token);
|
||||
|
||||
@@ -77,7 +77,7 @@ public class UsernamePasswordAuthentication implements ClientAuthentication, Aut
|
||||
Map<String, Object> body = createLoginBody(options);
|
||||
|
||||
return AuthenticationSteps.fromSupplier(() -> body)
|
||||
.login(String.format("%s/%s", getLoginPath(options.getPath()), options.getUsername()));
|
||||
.login(String.format("%s/%s", getLoginPath(options.getPath()), options.getUsername()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -132,13 +132,16 @@ public class ClientHttpConnectorFactory {
|
||||
if (hasSslConfiguration(sslConfiguration)) {
|
||||
|
||||
Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient()
|
||||
.configure(it -> configureSsl(sslConfiguration, it)).get();
|
||||
.configure(it -> configureSsl(sslConfiguration, it))
|
||||
.get();
|
||||
|
||||
client = client.secure(builder -> builder.sslContext(sslContextSpec));
|
||||
}
|
||||
|
||||
client = client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
|
||||
Math.toIntExact(options.getConnectionTimeout().toMillis())).proxyWithSystemProperties();
|
||||
client = client
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
|
||||
Math.toIntExact(options.getConnectionTimeout().toMillis()))
|
||||
.proxyWithSystemProperties();
|
||||
|
||||
return client;
|
||||
}
|
||||
@@ -149,7 +152,7 @@ public class ClientHttpConnectorFactory {
|
||||
|
||||
if (sslConfiguration.getTrustStoreConfiguration().isPresent()) {
|
||||
sslContextBuilder
|
||||
.trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()));
|
||||
.trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()));
|
||||
}
|
||||
|
||||
if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
|
||||
@@ -227,16 +230,18 @@ public class ClientHttpConnectorFactory {
|
||||
}, null);
|
||||
|
||||
PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder //
|
||||
.create().setTlsStrategy(tlsStrategy) //
|
||||
.build(); //
|
||||
.create()
|
||||
.setTlsStrategy(tlsStrategy) //
|
||||
.build(); //
|
||||
httpClientBuilder.setConnectionManager(connectionManager);
|
||||
}
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(Timeout.ofMilliseconds(options.getConnectionTimeout().toMillis()))
|
||||
.setResponseTimeout(Timeout.ofMilliseconds(options.getReadTimeout().toMillis()))
|
||||
.setAuthenticationEnabled(true) //
|
||||
.setRedirectsEnabled(true).build();
|
||||
.setConnectTimeout(Timeout.ofMilliseconds(options.getConnectionTimeout().toMillis()))
|
||||
.setResponseTimeout(Timeout.ofMilliseconds(options.getReadTimeout().toMillis()))
|
||||
.setAuthenticationEnabled(true) //
|
||||
.setRedirectsEnabled(true)
|
||||
.build();
|
||||
|
||||
httpClientBuilder.setDefaultRequestConfig(requestConfig);
|
||||
|
||||
@@ -283,13 +288,13 @@ public class ClientHttpConnectorFactory {
|
||||
|
||||
if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
|
||||
KeyStore keyStore = ClientHttpRequestFactoryFactory
|
||||
.getKeyStore(sslConfiguration.getKeyStoreConfiguration());
|
||||
.getKeyStore(sslConfiguration.getKeyStoreConfiguration());
|
||||
sslContextFactory.setKeyStore(keyStore);
|
||||
}
|
||||
|
||||
if (sslConfiguration.getTrustStoreConfiguration().isPresent()) {
|
||||
KeyStore keyStore = ClientHttpRequestFactoryFactory
|
||||
.getKeyStore(sslConfiguration.getTrustStoreConfiguration());
|
||||
.getKeyStore(sslConfiguration.getTrustStoreConfiguration());
|
||||
sslContextFactory.setTrustStore(keyStore);
|
||||
}
|
||||
|
||||
@@ -305,12 +310,12 @@ public class ClientHttpConnectorFactory {
|
||||
|
||||
if (!sslConfiguration.getEnabledProtocols().isEmpty()) {
|
||||
sslContextFactory
|
||||
.setIncludeProtocols(sslConfiguration.getEnabledProtocols().toArray(new String[0]));
|
||||
.setIncludeProtocols(sslConfiguration.getEnabledProtocols().toArray(new String[0]));
|
||||
}
|
||||
|
||||
if (!sslConfiguration.getEnabledCipherSuites().isEmpty()) {
|
||||
sslContextFactory
|
||||
.setIncludeCipherSuites(sslConfiguration.getEnabledCipherSuites().toArray(new String[0]));
|
||||
.setIncludeCipherSuites(sslConfiguration.getEnabledCipherSuites().toArray(new String[0]));
|
||||
}
|
||||
|
||||
ClientConnector connector = new ClientConnector();
|
||||
@@ -369,8 +374,9 @@ public class ClientHttpConnectorFactory {
|
||||
builder.sslContext(sslContext).sslParameters(parameters);
|
||||
}
|
||||
|
||||
builder.proxy(ProxySelector.getDefault()).followRedirects(java.net.http.HttpClient.Redirect.ALWAYS)
|
||||
.connectTimeout(options.getConnectionTimeout());
|
||||
builder.proxy(ProxySelector.getDefault())
|
||||
.followRedirects(java.net.http.HttpClient.Redirect.ALWAYS)
|
||||
.connectTimeout(options.getConnectionTimeout());
|
||||
return builder;
|
||||
}
|
||||
|
||||
|
||||
@@ -206,7 +206,7 @@ public class ClientHttpRequestFactoryFactory {
|
||||
KeyStore trustStore = getKeyStore(keyStoreConfiguration);
|
||||
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory
|
||||
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
trustManagerFactory.init(trustStore);
|
||||
|
||||
return trustManagerFactory;
|
||||
@@ -317,17 +317,20 @@ public class ClientHttpRequestFactoryFactory {
|
||||
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
|
||||
enabledProtocols, enabledCipherSuites, HttpsSupport.getDefaultHostnameVerifier());
|
||||
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder //
|
||||
.create().setSSLSocketFactory(sslSocketFactory) //
|
||||
.setDefaultSocketConfig(SocketConfig.custom() //
|
||||
.setSoTimeout(Timeout.ofMilliseconds(options.getReadTimeout().toMillis())).build()) //
|
||||
.build(); //
|
||||
.create()
|
||||
.setSSLSocketFactory(sslSocketFactory) //
|
||||
.setDefaultSocketConfig(SocketConfig.custom() //
|
||||
.setSoTimeout(Timeout.ofMilliseconds(options.getReadTimeout().toMillis()))
|
||||
.build()) //
|
||||
.build(); //
|
||||
httpClientBuilder.setConnectionManager(connectionManager);
|
||||
}
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(Timeout.ofMilliseconds(options.getConnectionTimeout().toMillis()))
|
||||
.setAuthenticationEnabled(true) //
|
||||
.setRedirectsEnabled(true).build();
|
||||
.setConnectTimeout(Timeout.ofMilliseconds(options.getConnectionTimeout().toMillis()))
|
||||
.setAuthenticationEnabled(true) //
|
||||
.setRedirectsEnabled(true)
|
||||
.build();
|
||||
|
||||
httpClientBuilder.setDefaultRequestConfig(requestConfig);
|
||||
return httpClientBuilder;
|
||||
@@ -387,7 +390,7 @@ public class ClientHttpRequestFactoryFactory {
|
||||
|
||||
if (!sslConfiguration.getEnabledCipherSuites().isEmpty()) {
|
||||
sslConnectionSpecBuilder
|
||||
.cipherSuites(sslConfiguration.getEnabledCipherSuites().toArray(new String[0]));
|
||||
.cipherSuites(sslConfiguration.getEnabledCipherSuites().toArray(new String[0]));
|
||||
}
|
||||
|
||||
sslConnectionSpec = sslConnectionSpecBuilder.build();
|
||||
@@ -398,7 +401,7 @@ public class ClientHttpRequestFactoryFactory {
|
||||
builder.connectionSpecs(Arrays.asList(sslConnectionSpec, ConnectionSpec.CLEARTEXT));
|
||||
|
||||
builder.connectTimeout(options.getConnectionTimeout().toMillis(), TimeUnit.MILLISECONDS)
|
||||
.readTimeout(options.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS);
|
||||
.readTimeout(options.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS);
|
||||
return builder;
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ public class ReactiveVaultClients {
|
||||
simpleSource = true;
|
||||
|
||||
UriBuilderFactory uriBuilderFactory = VaultClients
|
||||
.createUriBuilderFactory(((VaultEndpointProviderAdapter) endpointProvider).source);
|
||||
.createUriBuilderFactory(((VaultEndpointProviderAdapter) endpointProvider).source);
|
||||
builder.uriBuilderFactory(uriBuilderFactory);
|
||||
}
|
||||
}
|
||||
@@ -143,9 +143,13 @@ public class ReactiveVaultClients {
|
||||
|
||||
return endpointProvider.getVaultEndpoint().flatMap(endpoint -> {
|
||||
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUri(uri).scheme(endpoint.getScheme())
|
||||
.host(endpoint.getHost()).port(endpoint.getPort()).replacePath(endpoint.getPath())
|
||||
.path(VaultClients.normalizePath(endpoint.getPath(), uri.getPath())).build();
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUri(uri)
|
||||
.scheme(endpoint.getScheme())
|
||||
.host(endpoint.getHost())
|
||||
.port(endpoint.getPort())
|
||||
.replacePath(endpoint.getPath())
|
||||
.path(VaultClients.normalizePath(endpoint.getPath(), uri.getPath()))
|
||||
.build();
|
||||
|
||||
ClientRequest requestToSend = ClientRequest.from(request).url(uriComponents.toUri()).build();
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ public class RestTemplateBuilder {
|
||||
private @Nullable VaultEndpointProvider endpointProvider;
|
||||
|
||||
private Supplier<ClientHttpRequestFactory> requestFactory = () -> ClientHttpRequestFactoryFactory
|
||||
.create(new ClientOptions(), SslConfiguration.unconfigured());
|
||||
.create(new ClientOptions(), SslConfiguration.unconfigured());
|
||||
|
||||
private @Nullable ResponseErrorHandler errorHandler;
|
||||
|
||||
|
||||
@@ -176,7 +176,8 @@ public class VaultClients {
|
||||
|
||||
String baseUri = toBaseUri(endpoint);
|
||||
UriComponents uriComponents = UriComponentsBuilder
|
||||
.fromUriString(prepareUriTemplate(baseUri, uriTemplate)).build();
|
||||
.fromUriString(prepareUriTemplate(baseUri, uriTemplate))
|
||||
.build();
|
||||
|
||||
return UriComponentsBuilder.fromUriString(baseUri).uriComponents(uriComponents);
|
||||
}
|
||||
|
||||
@@ -194,12 +194,12 @@ public class WebClientBuilder {
|
||||
Map<String, String> defaultHeaders = this.defaultHeaders;
|
||||
builder.filter((request, next) -> {
|
||||
|
||||
return next.exchange(
|
||||
ClientRequest.from(request).headers(headers -> defaultHeaders.forEach((key, value) -> {
|
||||
if (!headers.containsKey(key)) {
|
||||
headers.add(key, value);
|
||||
}
|
||||
})).build());
|
||||
return next
|
||||
.exchange(ClientRequest.from(request).headers(headers -> defaultHeaders.forEach((key, value) -> {
|
||||
if (!headers.containsKey(key)) {
|
||||
headers.add(key, value);
|
||||
}
|
||||
})).build());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -105,8 +105,9 @@ public abstract class AbstractReactiveVaultConfiguration extends AbstractVaultCo
|
||||
|
||||
ObjectProvider<WebClientCustomizer> customizers = getBeanFactory().getBeanProvider(WebClientCustomizer.class);
|
||||
|
||||
WebClientBuilder builder = WebClientBuilder.builder().endpointProvider(endpointProvider)
|
||||
.httpConnector(httpConnector);
|
||||
WebClientBuilder builder = WebClientBuilder.builder()
|
||||
.endpointProvider(endpointProvider)
|
||||
.httpConnector(httpConnector);
|
||||
|
||||
builder.customizers(customizers.stream().toArray(WebClientCustomizer[]::new));
|
||||
|
||||
|
||||
@@ -92,10 +92,11 @@ public abstract class AbstractVaultConfiguration implements ApplicationContextAw
|
||||
ClientHttpRequestFactory requestFactory) {
|
||||
|
||||
ObjectProvider<RestTemplateCustomizer> customizers = getBeanFactory()
|
||||
.getBeanProvider(RestTemplateCustomizer.class);
|
||||
.getBeanProvider(RestTemplateCustomizer.class);
|
||||
|
||||
RestTemplateBuilder builder = RestTemplateBuilder.builder().endpointProvider(endpointProvider)
|
||||
.requestFactory(requestFactory);
|
||||
RestTemplateBuilder builder = RestTemplateBuilder.builder()
|
||||
.endpointProvider(endpointProvider)
|
||||
.requestFactory(requestFactory);
|
||||
|
||||
builder.customizers(customizers.stream().toArray(RestTemplateCustomizer[]::new));
|
||||
|
||||
|
||||
@@ -258,33 +258,33 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
public ClientAuthentication clientAuthentication() {
|
||||
|
||||
String authentication = getProperty("vault.authentication", AuthenticationMethod.TOKEN.name()).toUpperCase()
|
||||
.replace('-', '_');
|
||||
.replace('-', '_');
|
||||
|
||||
AuthenticationMethod authenticationMethod = AuthenticationMethod.valueOf(authentication);
|
||||
|
||||
switch (authenticationMethod) {
|
||||
|
||||
case TOKEN:
|
||||
return tokenAuthentication();
|
||||
case APPID:
|
||||
return appIdAuthentication();
|
||||
case APPROLE:
|
||||
return appRoleAuthentication();
|
||||
case AWS_EC2:
|
||||
return awsEc2Authentication();
|
||||
case AWS_IAM:
|
||||
return awsIamAuthentication();
|
||||
case AZURE:
|
||||
return azureMsiAuthentication();
|
||||
case CERT:
|
||||
return new ClientCertificateAuthentication(restOperations());
|
||||
case CUBBYHOLE:
|
||||
return cubbyholeAuthentication();
|
||||
case KUBERNETES:
|
||||
return kubeAuthentication();
|
||||
default:
|
||||
throw new IllegalStateException(String.format("Vault authentication method %s is not supported with %s",
|
||||
authenticationMethod, getClass().getSimpleName()));
|
||||
case TOKEN:
|
||||
return tokenAuthentication();
|
||||
case APPID:
|
||||
return appIdAuthentication();
|
||||
case APPROLE:
|
||||
return appRoleAuthentication();
|
||||
case AWS_EC2:
|
||||
return awsEc2Authentication();
|
||||
case AWS_IAM:
|
||||
return awsIamAuthentication();
|
||||
case AZURE:
|
||||
return azureMsiAuthentication();
|
||||
case CERT:
|
||||
return new ClientCertificateAuthentication(restOperations());
|
||||
case CUBBYHOLE:
|
||||
return cubbyholeAuthentication();
|
||||
case KUBERNETES:
|
||||
return kubeAuthentication();
|
||||
default:
|
||||
throw new IllegalStateException(String.format("Vault authentication method %s is not supported with %s",
|
||||
authenticationMethod, getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,8 +310,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
Assert.hasText(appId, "Vault AppId authentication: AppId (vault.app-id.app-id) must not be empty");
|
||||
Assert.hasText(userId, "Vault AppId authentication: UserId (vault.app-id.user-id) must not be empty");
|
||||
|
||||
AppIdAuthenticationOptionsBuilder builder = AppIdAuthenticationOptions.builder().appId(appId)
|
||||
.userIdMechanism(getAppIdUserIdMechanism(userId)).path(path);
|
||||
AppIdAuthenticationOptionsBuilder builder = AppIdAuthenticationOptions.builder()
|
||||
.appId(appId)
|
||||
.userIdMechanism(getAppIdUserIdMechanism(userId))
|
||||
.path(path);
|
||||
|
||||
return new AppIdAuthentication(builder.build(), restOperations());
|
||||
}
|
||||
@@ -326,7 +328,8 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
Assert.hasText(roleId, "Vault AppRole authentication: RoleId (vault.app-role.role-id) must not be empty");
|
||||
|
||||
AppRoleAuthenticationOptionsBuilder builder = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId)).path(path);
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.path(path);
|
||||
|
||||
if (StringUtils.hasText(secretId)) {
|
||||
builder = builder.secretId(SecretId.provided(secretId));
|
||||
@@ -370,7 +373,8 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
}
|
||||
|
||||
AwsEc2AuthenticationOptionsBuilder builder = AwsEc2AuthenticationOptions.builder()
|
||||
.role(StringUtils.hasText(role) ? role : roleId).path(path);
|
||||
.role(StringUtils.hasText(role) ? role : roleId)
|
||||
.path(path);
|
||||
|
||||
if (StringUtils.hasText(identityDocument)) {
|
||||
builder.identityDocumentUri(URI.create(identityDocument));
|
||||
@@ -385,8 +389,9 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
Assert.isTrue(StringUtils.hasText(role),
|
||||
"Vault AWS-IAM authentication: Role (vault.aws-iam.role) must not be empty");
|
||||
|
||||
AwsIamAuthenticationOptionsBuilder builder = AwsIamAuthenticationOptions.builder().role(role)
|
||||
.credentialsProvider(DefaultCredentialsProvider.create());
|
||||
AwsIamAuthenticationOptionsBuilder builder = AwsIamAuthenticationOptions.builder()
|
||||
.role(role)
|
||||
.credentialsProvider(DefaultCredentialsProvider.create());
|
||||
|
||||
return new AwsIamAuthentication(builder.build(), restOperations());
|
||||
}
|
||||
@@ -402,8 +407,11 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI);
|
||||
Assert.hasText(role, "Vault Azure MSI authentication: Role (vault.azure-msi.role) must not be empty");
|
||||
|
||||
AzureMsiAuthenticationOptionsBuilder builder = AzureMsiAuthenticationOptions.builder().role(role).path(path)
|
||||
.instanceMetadataUri(metadataServiceUri).identityTokenServiceUri(identityTokenServiceUri);
|
||||
AzureMsiAuthenticationOptionsBuilder builder = AzureMsiAuthenticationOptions.builder()
|
||||
.role(role)
|
||||
.path(path)
|
||||
.instanceMetadataUri(metadataServiceUri)
|
||||
.identityTokenServiceUri(identityTokenServiceUri);
|
||||
|
||||
return new AzureMsiAuthentication(builder.build(), restOperations());
|
||||
}
|
||||
@@ -413,8 +421,9 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
String token = getProperty("vault.token");
|
||||
Assert.hasText(token, "Vault Cubbyhole authentication: Initial token (vault.token) must not be empty");
|
||||
|
||||
CubbyholeAuthenticationOptionsBuilder builder = CubbyholeAuthenticationOptions.builder().wrapped()
|
||||
.initialToken(VaultToken.of(token));
|
||||
CubbyholeAuthenticationOptionsBuilder builder = CubbyholeAuthenticationOptions.builder()
|
||||
.wrapped()
|
||||
.initialToken(VaultToken.of(token));
|
||||
|
||||
return new CubbyholeAuthentication(builder.build(), restOperations());
|
||||
}
|
||||
@@ -431,8 +440,10 @@ public class EnvironmentVaultConfiguration extends AbstractVaultConfiguration im
|
||||
|
||||
KubernetesJwtSupplier jwtSupplier = new KubernetesServiceAccountTokenFile(tokenFile);
|
||||
|
||||
KubernetesAuthenticationOptionsBuilder builder = KubernetesAuthenticationOptions.builder().role(role)
|
||||
.jwtSupplier(jwtSupplier).path(path);
|
||||
KubernetesAuthenticationOptionsBuilder builder = KubernetesAuthenticationOptions.builder()
|
||||
.role(role)
|
||||
.jwtSupplier(jwtSupplier)
|
||||
.path(path);
|
||||
|
||||
return new KubernetesAuthentication(builder.build(), restOperations());
|
||||
}
|
||||
|
||||
@@ -211,8 +211,11 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations {
|
||||
|
||||
ExchangeFilterFunction filter = getSessionFilter();
|
||||
|
||||
return WebClientBuilder.builder().httpConnector(connector).endpointProvider(endpointProvider).filter(filter)
|
||||
.build();
|
||||
return WebClientBuilder.builder()
|
||||
.httpConnector(connector)
|
||||
.endpointProvider(endpointProvider)
|
||||
.filter(filter)
|
||||
.build();
|
||||
}
|
||||
|
||||
private ExchangeFilterFunction getSessionFilter() {
|
||||
@@ -254,7 +257,7 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations {
|
||||
VaultListResponse.class);
|
||||
|
||||
return read.filter(response -> response.getData() != null && response.getData().containsKey("keys"))
|
||||
.flatMapIterable(response -> (List<String>) response.getRequiredData().get("keys"));
|
||||
.flatMapIterable(response -> (List<String>) response.getRequiredData().get("keys"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -279,8 +282,9 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations {
|
||||
|
||||
Assert.hasText(path, "Path must not be empty");
|
||||
|
||||
return doWithSession(webClient -> webClient.delete().uri(path)
|
||||
.exchangeToMono(mapResponse(String.class, path, HttpMethod.DELETE))).then();
|
||||
return doWithSession(webClient -> webClient.delete()
|
||||
.uri(path)
|
||||
.exchangeToMono(mapResponse(String.class, path, HttpMethod.DELETE))).then();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -314,7 +318,8 @@ public class ReactiveVaultTemplate implements ReactiveVaultOperations {
|
||||
private <T> Mono<T> doRead(String path, Class<T> responseType) {
|
||||
|
||||
return doWithSession(client -> client.get() //
|
||||
.uri(path).exchangeToMono(mapResponse(responseType, path, HttpMethod.GET)));
|
||||
.uri(path)
|
||||
.exchangeToMono(mapResponse(responseType, path, HttpMethod.GET)));
|
||||
}
|
||||
|
||||
private static <T> Function<ClientResponse, Mono<T>> mapResponse(Class<T> bodyType, String path,
|
||||
|
||||
@@ -102,7 +102,7 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport {
|
||||
<I, T> T doRead(String path, Class<I> deserializeAs, BiFunction<VaultResponseSupport<?>, I, T> mappingFunction) {
|
||||
|
||||
ParameterizedTypeReference<VaultResponseSupport<JsonNode>> ref = VaultResponses
|
||||
.getTypeReference(JsonNode.class);
|
||||
.getTypeReference(JsonNode.class);
|
||||
|
||||
VaultResponseSupport<JsonNode> response = doRead(createDataPath(path), ref);
|
||||
|
||||
@@ -191,7 +191,7 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport {
|
||||
|
||||
return this.vaultOperations.doWithSession((restOperations) -> {
|
||||
return restOperations.exchange(path, HttpMethod.POST, new HttpEntity<>(body), VaultResponse.class)
|
||||
.getBody();
|
||||
.getBody();
|
||||
});
|
||||
}
|
||||
catch (HttpStatusCodeException e) {
|
||||
@@ -221,9 +221,10 @@ abstract class VaultKeyValueAccessor implements VaultKeyValueOperationsSupport {
|
||||
RestTemplate template = (RestTemplate) operations;
|
||||
|
||||
Optional<AbstractJackson2HttpMessageConverter> jackson2Converter = template.getMessageConverters()
|
||||
.stream().filter(AbstractJackson2HttpMessageConverter.class::isInstance) //
|
||||
.map(AbstractJackson2HttpMessageConverter.class::cast) //
|
||||
.findFirst();
|
||||
.stream()
|
||||
.filter(AbstractJackson2HttpMessageConverter.class::isInstance) //
|
||||
.map(AbstractJackson2HttpMessageConverter.class::cast) //
|
||||
.findFirst();
|
||||
|
||||
return jackson2Converter.map(AbstractJackson2HttpMessageConverter::getObjectMapper);
|
||||
}
|
||||
|
||||
@@ -90,20 +90,23 @@ class VaultKeyValueMetadataTemplate implements VaultKeyValueMetadataOperations {
|
||||
Duration duration = DurationParser.parseDuration((String) metadataResponse.get("delete_version_after"));
|
||||
|
||||
return VaultMetadataResponse.builder()
|
||||
.casRequired(Boolean.parseBoolean(String.valueOf(metadataResponse.get("cas_required"))))
|
||||
.createdTime(toInstant((String) metadataResponse.get("created_time")))
|
||||
.currentVersion(Integer.parseInt(String.valueOf(metadataResponse.get("current_version"))))
|
||||
.deleteVersionAfter(duration)
|
||||
.maxVersions(Integer.parseInt(String.valueOf(metadataResponse.get("max_versions"))))
|
||||
.oldestVersion(Integer.parseInt(String.valueOf(metadataResponse.get("oldest_version"))))
|
||||
.updatedTime(toInstant((String) metadataResponse.get("updated_time")))
|
||||
.versions(buildVersions((Map) metadataResponse.get("versions"))).build();
|
||||
.casRequired(Boolean.parseBoolean(String.valueOf(metadataResponse.get("cas_required"))))
|
||||
.createdTime(toInstant((String) metadataResponse.get("created_time")))
|
||||
.currentVersion(Integer.parseInt(String.valueOf(metadataResponse.get("current_version"))))
|
||||
.deleteVersionAfter(duration)
|
||||
.maxVersions(Integer.parseInt(String.valueOf(metadataResponse.get("max_versions"))))
|
||||
.oldestVersion(Integer.parseInt(String.valueOf(metadataResponse.get("oldest_version"))))
|
||||
.updatedTime(toInstant((String) metadataResponse.get("updated_time")))
|
||||
.versions(buildVersions((Map) metadataResponse.get("versions")))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static List<Versioned.Metadata> buildVersions(Map<String, Map<String, Object>> versions) {
|
||||
|
||||
return versions.entrySet().stream().map(entry -> buildVersion(entry.getKey(), entry.getValue()))
|
||||
.collect(Collectors.toList());
|
||||
return versions.entrySet()
|
||||
.stream()
|
||||
.map(entry -> buildVersion(entry.getKey(), entry.getValue()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static Versioned.Metadata buildVersion(String version, Map<String, Object> versionData) {
|
||||
@@ -113,8 +116,12 @@ class VaultKeyValueMetadataTemplate implements VaultKeyValueMetadataOperations {
|
||||
boolean destroyed = (Boolean) versionData.get("destroyed");
|
||||
Versioned.Version kvVersion = Versioned.Version.from(Integer.parseInt(version));
|
||||
|
||||
return Versioned.Metadata.builder().createdAt(createdTime).deletedAt(deletionTime).destroyed(destroyed)
|
||||
.version(kvVersion).build();
|
||||
return Versioned.Metadata.builder()
|
||||
.createdAt(createdTime)
|
||||
.deletedAt(deletionTime)
|
||||
.destroyed(destroyed)
|
||||
.version(kvVersion)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
@@ -162,17 +162,26 @@ public class VaultPkiTemplate implements VaultPkiOperations {
|
||||
PropertyMapper mapper = PropertyMapper.get();
|
||||
|
||||
mapper.from(certificateRequest::getCommonName).to("common_name", request);
|
||||
mapper.from(certificateRequest::getAltNames).whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ",")).to("alt_names", request);
|
||||
mapper.from(certificateRequest::getIpSubjectAltNames).whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ",")).to("ip_sans", request);
|
||||
mapper.from(certificateRequest::getUriSubjectAltNames).whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ",")).to("uri_sans", request);
|
||||
mapper.from(certificateRequest::getOtherSans).whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ",")).to("other_sans", request);
|
||||
mapper.from(certificateRequest::getAltNames)
|
||||
.whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ","))
|
||||
.to("alt_names", request);
|
||||
mapper.from(certificateRequest::getIpSubjectAltNames)
|
||||
.whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ","))
|
||||
.to("ip_sans", request);
|
||||
mapper.from(certificateRequest::getUriSubjectAltNames)
|
||||
.whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ","))
|
||||
.to("uri_sans", request);
|
||||
mapper.from(certificateRequest::getOtherSans)
|
||||
.whenNotEmpty()
|
||||
.as(i -> StringUtils.collectionToDelimitedString(i, ","))
|
||||
.to("other_sans", request);
|
||||
mapper.from(certificateRequest::getTtl).whenNonNull().as(i -> i.get(ChronoUnit.SECONDS)).to("ttl", request);
|
||||
mapper.from(certificateRequest::isExcludeCommonNameFromSubjectAltNames).whenTrue().to("exclude_cn_from_sans",
|
||||
request);
|
||||
mapper.from(certificateRequest::isExcludeCommonNameFromSubjectAltNames)
|
||||
.whenTrue()
|
||||
.to("exclude_cn_from_sans", request);
|
||||
mapper.from(certificateRequest::getFormat).whenHasText().to("format", request);
|
||||
mapper.from(certificateRequest::getPrivateKeyFormat).whenHasText().to("private_key_format", request);
|
||||
|
||||
|
||||
@@ -362,8 +362,8 @@ public class VaultSysTemplate implements VaultSysOperations {
|
||||
if (map.containsKey("type")) {
|
||||
|
||||
VaultMountBuilder builder = VaultMount.builder() //
|
||||
.type((String) map.get("type")) //
|
||||
.description((String) map.get("description"));// ;
|
||||
.type((String) map.get("type")) //
|
||||
.description((String) map.get("description"));// ;
|
||||
|
||||
if (map.containsKey("config")) {
|
||||
builder.config((Map) map.get("config"));
|
||||
|
||||
@@ -240,8 +240,11 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa
|
||||
protected RestTemplate doCreateSessionTemplate(VaultEndpointProvider endpointProvider,
|
||||
ClientHttpRequestFactory requestFactory) {
|
||||
|
||||
return RestTemplateBuilder.builder().endpointProvider(endpointProvider).requestFactory(requestFactory)
|
||||
.customizers(restTemplate -> restTemplate.getInterceptors().add(getSessionInterceptor())).build();
|
||||
return RestTemplateBuilder.builder()
|
||||
.endpointProvider(endpointProvider)
|
||||
.requestFactory(requestFactory)
|
||||
.customizers(restTemplate -> restTemplate.getInterceptors().add(getSessionInterceptor()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private ClientHttpRequestInterceptor getSessionInterceptor() {
|
||||
@@ -284,10 +287,10 @@ public class VaultTemplate implements InitializingBean, VaultOperations, Disposa
|
||||
public VaultKeyValueOperations opsForKeyValue(String path, KeyValueBackend apiVersion) {
|
||||
|
||||
switch (apiVersion) {
|
||||
case KV_1:
|
||||
return new VaultKeyValue1Template(this, path);
|
||||
case KV_2:
|
||||
return new VaultKeyValue2Template(this, path);
|
||||
case KV_1:
|
||||
return new VaultKeyValue1Template(this, path);
|
||||
case KV_2:
|
||||
return new VaultKeyValue2Template(this, path);
|
||||
}
|
||||
|
||||
throw new UnsupportedOperationException(
|
||||
|
||||
@@ -72,7 +72,8 @@ public class VaultTransformTemplate implements VaultTransformOperations {
|
||||
request.put("value", plaintext);
|
||||
|
||||
return (String) this.vaultOperations.write(String.format("%s/encode/%s", this.path, roleName), request)
|
||||
.getRequiredData().get("encoded_value");
|
||||
.getRequiredData()
|
||||
.get("encoded_value");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -88,7 +89,8 @@ public class VaultTransformTemplate implements VaultTransformOperations {
|
||||
applyTransformOptions(plaintext.getContext(), request);
|
||||
|
||||
Map<String, Object> data = this.vaultOperations
|
||||
.write(String.format("%s/encode/%s", this.path, roleName), request).getRequiredData();
|
||||
.write(String.format("%s/encode/%s", this.path, roleName), request)
|
||||
.getRequiredData();
|
||||
|
||||
return toCiphertext(data, plaintext.getContext());
|
||||
}
|
||||
@@ -143,7 +145,8 @@ public class VaultTransformTemplate implements VaultTransformOperations {
|
||||
applyTransformOptions(transformContext, request);
|
||||
|
||||
return (String) this.vaultOperations.write(String.format("%s/decode/%s", this.path, roleName), request)
|
||||
.getRequiredData().get("decoded_value");
|
||||
.getRequiredData()
|
||||
.get("decoded_value");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -258,8 +261,10 @@ public class VaultTransformTemplate implements VaultTransformOperations {
|
||||
VaultTransformContext contextToUse = context;
|
||||
if (data.containsKey("tweak")) {
|
||||
byte[] tweak = Base64Utils.decodeFromString((String) data.get("tweak"));
|
||||
contextToUse = VaultTransformContext.builder().transformation(context.getTransformation()).tweak(tweak)
|
||||
.build();
|
||||
contextToUse = VaultTransformContext.builder()
|
||||
.transformation(context.getTransformation())
|
||||
.tweak(tweak)
|
||||
.build();
|
||||
}
|
||||
|
||||
return contextToUse.isEmpty() ? TransformCiphertext.of(ciphertext)
|
||||
|
||||
@@ -122,7 +122,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
Assert.notNull(type, "Key type must not be null");
|
||||
|
||||
VaultResponseSupport<RawTransitKeyImpl> result = this.vaultOperations
|
||||
.read(String.format("%s/export/%s/%s", this.path, type.getValue(), keyName), RawTransitKeyImpl.class);
|
||||
.read(String.format("%s/export/%s/%s", this.path, type.getValue(), keyName), RawTransitKeyImpl.class);
|
||||
|
||||
return result != null ? result.getRequiredData() : null;
|
||||
}
|
||||
@@ -134,7 +134,7 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
Assert.hasText(keyName, "Key name must not be empty");
|
||||
|
||||
VaultResponseSupport<VaultTransitKeyImpl> result = this.vaultOperations
|
||||
.read(String.format("%s/keys/%s", this.path, keyName), VaultTransitKeyImpl.class);
|
||||
.read(String.format("%s/keys/%s", this.path, keyName), VaultTransitKeyImpl.class);
|
||||
|
||||
if (result != null) {
|
||||
return result.getRequiredData();
|
||||
@@ -170,7 +170,8 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
request.put("plaintext", Base64Utils.encodeToString(plaintext.getBytes()));
|
||||
|
||||
return (String) this.vaultOperations.write(String.format("%s/encrypt/%s", this.path, keyName), request)
|
||||
.getRequiredData().get("ciphertext");
|
||||
.getRequiredData()
|
||||
.get("ciphertext");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -198,7 +199,8 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
applyTransitOptions(transitContext, request);
|
||||
|
||||
return (String) this.vaultOperations.write(String.format("%s/encrypt/%s", this.path, keyName), request)
|
||||
.getRequiredData().get("ciphertext");
|
||||
.getRequiredData()
|
||||
.get("ciphertext");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -239,7 +241,9 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
request.put("ciphertext", ciphertext);
|
||||
|
||||
String plaintext = (String) this.vaultOperations
|
||||
.write(String.format("%s/decrypt/%s", this.path, keyName), request).getRequiredData().get("plaintext");
|
||||
.write(String.format("%s/decrypt/%s", this.path, keyName), request)
|
||||
.getRequiredData()
|
||||
.get("plaintext");
|
||||
|
||||
return new String(Base64Utils.decodeFromString(plaintext));
|
||||
}
|
||||
@@ -269,7 +273,9 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
applyTransitOptions(transitContext, request);
|
||||
|
||||
String plaintext = (String) this.vaultOperations
|
||||
.write(String.format("%s/decrypt/%s", this.path, keyName), request).getRequiredData().get("plaintext");
|
||||
.write(String.format("%s/decrypt/%s", this.path, keyName), request)
|
||||
.getRequiredData()
|
||||
.get("plaintext");
|
||||
|
||||
return Base64Utils.decodeFromString(plaintext);
|
||||
}
|
||||
@@ -311,7 +317,8 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
request.put("ciphertext", ciphertext);
|
||||
|
||||
return (String) this.vaultOperations.write(String.format("%s/rewrap/%s", this.path, keyName), request)
|
||||
.getRequiredData().get("ciphertext");
|
||||
.getRequiredData()
|
||||
.get("ciphertext");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -328,7 +335,8 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
applyTransitOptions(transitContext, request);
|
||||
|
||||
return (String) this.vaultOperations.write(String.format("%s/rewrap/%s", this.path, keyName), request)
|
||||
.getRequiredData().get("ciphertext");
|
||||
.getRequiredData()
|
||||
.get("ciphertext");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -356,7 +364,8 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
mapper.from(hmacRequest::getKeyVersion).whenNonNull().to("key_version", request);
|
||||
|
||||
String hmac = (String) this.vaultOperations.write(String.format("%s/hmac/%s", this.path, keyName), request)
|
||||
.getRequiredData().get("hmac");
|
||||
.getRequiredData()
|
||||
.get("hmac");
|
||||
|
||||
return Hmac.of(hmac);
|
||||
}
|
||||
@@ -386,7 +395,8 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
mapper.from(signRequest::getSignatureAlgorithm).whenHasText().to("signature_algorithm", request);
|
||||
|
||||
String signature = (String) this.vaultOperations.write(String.format("%s/sign/%s", this.path, keyName), request)
|
||||
.getRequiredData().get("signature");
|
||||
.getRequiredData()
|
||||
.get("signature");
|
||||
|
||||
return Signature.of(signature);
|
||||
}
|
||||
@@ -411,16 +421,20 @@ public class VaultTransitTemplate implements VaultTransitOperations {
|
||||
Map<String, Object> request = new LinkedHashMap<>(5);
|
||||
PropertyMapper mapper = PropertyMapper.get();
|
||||
|
||||
mapper.from(verificationRequest.getPlaintext()::getPlaintext).as(Base64Utils::encodeToString).to("input",
|
||||
request);
|
||||
mapper.from(verificationRequest.getPlaintext()::getPlaintext)
|
||||
.as(Base64Utils::encodeToString)
|
||||
.to("input", request);
|
||||
mapper.from(verificationRequest::getHmac).whenNonNull().as(Hmac::getHmac).to("hmac", request);
|
||||
mapper.from(verificationRequest::getSignature).whenNonNull().as(Signature::getSignature).to("signature",
|
||||
request);
|
||||
mapper.from(verificationRequest::getSignature)
|
||||
.whenNonNull()
|
||||
.as(Signature::getSignature)
|
||||
.to("signature", request);
|
||||
mapper.from(verificationRequest::getHashAlgorithm).whenHasText().to("hash_algorithm", request);
|
||||
mapper.from(verificationRequest::getSignatureAlgorithm).whenHasText().to("signature_algorithm", request);
|
||||
|
||||
Map<String, Object> response = this.vaultOperations
|
||||
.write(String.format("%s/verify/%s", this.path, keyName), request).getRequiredData();
|
||||
.write(String.format("%s/verify/%s", this.path, keyName), request)
|
||||
.getRequiredData();
|
||||
|
||||
if (response.containsKey("valid") && Boolean.valueOf("" + response.get("valid"))) {
|
||||
return SignatureValidation.valid();
|
||||
|
||||
@@ -208,8 +208,10 @@ public class VaultVersionedKeyValueTemplate extends VaultKeyValue2Accessor imple
|
||||
}
|
||||
|
||||
private static List<Integer> toVersionList(Version[] versionsToDelete) {
|
||||
return Arrays.stream(versionsToDelete).filter(Version::isVersioned).map(Version::getVersion)
|
||||
.collect(Collectors.toList());
|
||||
return Arrays.stream(versionsToDelete)
|
||||
.filter(Version::isVersioned)
|
||||
.map(Version::getVersion)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -92,7 +92,7 @@ public class VaultWrappingTemplate implements VaultWrappingOperations {
|
||||
|
||||
return doUnwrap(token, (restOperations, entity) -> {
|
||||
return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, entity, VaultResponse.class)
|
||||
.getBody();
|
||||
.getBody();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -156,8 +156,9 @@ public class VaultWrappingTemplate implements VaultWrappingOperations {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("X-Vault-Wrap-TTL", Long.toString(duration.getSeconds()));
|
||||
|
||||
return restOperations.exchange("sys/wrapping/wrap", HttpMethod.POST, new HttpEntity<>(body, headers),
|
||||
VaultResponse.class).getBody();
|
||||
return restOperations
|
||||
.exchange("sys/wrapping/wrap", HttpMethod.POST, new HttpEntity<>(body, headers), VaultResponse.class)
|
||||
.getBody();
|
||||
});
|
||||
|
||||
Map<String, String> wrapInfo = response.getWrapInfo();
|
||||
|
||||
@@ -123,7 +123,7 @@ import org.springframework.web.client.HttpStatusCodeException;
|
||||
public class SecretLeaseContainer extends SecretLeaseEventPublisher implements InitializingBean, DisposableBean {
|
||||
|
||||
private static final AtomicIntegerFieldUpdater<SecretLeaseContainer> UPDATER = AtomicIntegerFieldUpdater
|
||||
.newUpdater(SecretLeaseContainer.class, "status");
|
||||
.newUpdater(SecretLeaseContainer.class, "status");
|
||||
|
||||
private static final AtomicInteger poolId = new AtomicInteger();
|
||||
|
||||
@@ -432,8 +432,8 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements I
|
||||
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setDaemon(true);
|
||||
scheduler.setThreadNamePrefix(
|
||||
String.format("%s-%d-", getClass().getSimpleName(), poolId.incrementAndGet()));
|
||||
scheduler
|
||||
.setThreadNamePrefix(String.format("%s-%d-", getClass().getSimpleName(), poolId.incrementAndGet()));
|
||||
scheduler.afterPropertiesSet();
|
||||
|
||||
this.taskScheduler = scheduler;
|
||||
@@ -923,7 +923,7 @@ public class SecretLeaseContainer extends SecretLeaseEventPublisher implements I
|
||||
static class OneShotTrigger implements Trigger {
|
||||
|
||||
private static final AtomicIntegerFieldUpdater<OneShotTrigger> UPDATER = AtomicIntegerFieldUpdater
|
||||
.newUpdater(OneShotTrigger.class, "status");
|
||||
.newUpdater(OneShotTrigger.class, "status");
|
||||
|
||||
private static final int STATUS_ARMED = 0;
|
||||
|
||||
|
||||
@@ -263,7 +263,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter {
|
||||
}
|
||||
|
||||
return new VaultKeyValue1KeyspaceAccessor(mountInfo, it, this.vaultOperations
|
||||
.opsForKeyValue(mountInfo.getPath(), VaultKeyValueOperationsSupport.KeyValueBackend.KV_1));
|
||||
.opsForKeyValue(mountInfo.getPath(), VaultKeyValueOperationsSupport.KeyValueBackend.KV_1));
|
||||
});
|
||||
|
||||
}
|
||||
@@ -402,7 +402,7 @@ public class VaultKeyValueAdapter extends AbstractKeyValueAdapter {
|
||||
Versioned.Metadata metadata;
|
||||
if (secretDocument.getVersion() != null) {
|
||||
metadata = operations.put(createPath(secretDocument.getRequiredId()), Versioned
|
||||
.create(secretDocument.getBody(), Versioned.Version.from(secretDocument.getVersion())));
|
||||
.create(secretDocument.getBody(), Versioned.Version.from(secretDocument.getVersion())));
|
||||
}
|
||||
else {
|
||||
metadata = operations.put(createPath(secretDocument.getRequiredId()), secretDocument.getBody());
|
||||
|
||||
@@ -75,7 +75,7 @@ public class VaultQueryCreator extends AbstractQueryCreator<KeyValueQuery<VaultQ
|
||||
private Predicate<String> createPredicate(Part part, Iterator<Object> parameters) {
|
||||
|
||||
PersistentPropertyPath<VaultPersistentProperty> propertyPath = this.mappingContext
|
||||
.getPersistentPropertyPath(part.getProperty());
|
||||
.getPersistentPropertyPath(part.getProperty());
|
||||
|
||||
if (propertyPath.getLeafProperty() != null && !propertyPath.getLeafProperty().isIdProperty()) {
|
||||
throw new InvalidDataAccessApiUsageException(
|
||||
@@ -100,47 +100,49 @@ public class VaultQueryCreator extends AbstractQueryCreator<KeyValueQuery<VaultQ
|
||||
Type type = part.getType();
|
||||
|
||||
switch (type) {
|
||||
case AFTER:
|
||||
case GREATER_THAN:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) > 0);
|
||||
case GREATER_THAN_EQUAL:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) >= 0);
|
||||
case BEFORE:
|
||||
case LESS_THAN:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) < 0);
|
||||
case LESS_THAN_EQUAL:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) <= 0);
|
||||
case BETWEEN:
|
||||
case AFTER:
|
||||
case GREATER_THAN:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) > 0);
|
||||
case GREATER_THAN_EQUAL:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) >= 0);
|
||||
case BEFORE:
|
||||
case LESS_THAN:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) < 0);
|
||||
case LESS_THAN_EQUAL:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.compareTo(value) <= 0);
|
||||
case BETWEEN:
|
||||
|
||||
String from = accessor.nextString(parameters);
|
||||
String to = accessor.nextString(parameters);
|
||||
String from = accessor.nextString(parameters);
|
||||
String to = accessor.nextString(parameters);
|
||||
|
||||
return it -> it.compareTo(from) >= 0 && it.compareTo(to) <= 0;
|
||||
case NOT_IN:
|
||||
return new Criteria<>(accessor.nextAsArray(parameters), (value, it) -> Arrays.binarySearch(value, it) < 0);
|
||||
case IN:
|
||||
return new Criteria<>(accessor.nextAsArray(parameters), (value, it) -> Arrays.binarySearch(value, it) >= 0);
|
||||
case STARTING_WITH:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.startsWith(value));
|
||||
case ENDING_WITH:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.endsWith(value));
|
||||
case CONTAINING:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.contains(value));
|
||||
case NOT_CONTAINING:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> !it.contains(value));
|
||||
case REGEX:
|
||||
return Pattern.compile((String) parameters.next(), isIgnoreCase(part) ? Pattern.CASE_INSENSITIVE : 0)
|
||||
return it -> it.compareTo(from) >= 0 && it.compareTo(to) <= 0;
|
||||
case NOT_IN:
|
||||
return new Criteria<>(accessor.nextAsArray(parameters),
|
||||
(value, it) -> Arrays.binarySearch(value, it) < 0);
|
||||
case IN:
|
||||
return new Criteria<>(accessor.nextAsArray(parameters),
|
||||
(value, it) -> Arrays.binarySearch(value, it) >= 0);
|
||||
case STARTING_WITH:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.startsWith(value));
|
||||
case ENDING_WITH:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.endsWith(value));
|
||||
case CONTAINING:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.contains(value));
|
||||
case NOT_CONTAINING:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> !it.contains(value));
|
||||
case REGEX:
|
||||
return Pattern.compile((String) parameters.next(), isIgnoreCase(part) ? Pattern.CASE_INSENSITIVE : 0)
|
||||
.asPredicate();
|
||||
case TRUE:
|
||||
return it -> it.equalsIgnoreCase("true");
|
||||
case FALSE:
|
||||
return it -> it.equalsIgnoreCase("false");
|
||||
case SIMPLE_PROPERTY:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.equals(value));
|
||||
case NEGATING_SIMPLE_PROPERTY:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> !it.equals(value));
|
||||
default:
|
||||
throw new IllegalArgumentException("Unsupported keyword!");
|
||||
case TRUE:
|
||||
return it -> it.equalsIgnoreCase("true");
|
||||
case FALSE:
|
||||
return it -> it.equalsIgnoreCase("false");
|
||||
case SIMPLE_PROPERTY:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> it.equals(value));
|
||||
case NEGATING_SIMPLE_PROPERTY:
|
||||
return new Criteria<>(accessor.nextString(parameters), (value, it) -> !it.equals(value));
|
||||
default:
|
||||
throw new IllegalArgumentException("Unsupported keyword!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ public class VaultRepositoryFactory extends KeyValueRepositoryFactory {
|
||||
VaultKeyValueTemplate template = (VaultKeyValueTemplate) operations;
|
||||
|
||||
VaultPersistentEntity<?> entity = (VaultPersistentEntity<?>) this.operations.getMappingContext()
|
||||
.getRequiredPersistentEntity(metadata.getDomainType());
|
||||
.getRequiredPersistentEntity(metadata.getDomainType());
|
||||
EntityInformation<?, String> entityInformation = getEntityInformation(metadata.getDomainType());
|
||||
VaultRevisionRepository<?> repository = new VaultRevisionRepository<>(entityInformation,
|
||||
entity.getKeySpace(), template);
|
||||
@@ -87,7 +87,7 @@ public class VaultRepositoryFactory extends KeyValueRepositoryFactory {
|
||||
public <T, ID> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
|
||||
|
||||
VaultPersistentEntity<T> entity = (VaultPersistentEntity<T>) this.operations.getMappingContext()
|
||||
.getRequiredPersistentEntity(domainClass);
|
||||
.getRequiredPersistentEntity(domainClass);
|
||||
|
||||
return new MappingVaultEntityInformation<>(entity);
|
||||
}
|
||||
|
||||
@@ -324,10 +324,10 @@ public class CertificateBundle extends Certificate {
|
||||
throws GeneralSecurityException, IOException {
|
||||
|
||||
switch (keyType.toLowerCase(Locale.ROOT)) {
|
||||
case "rsa":
|
||||
return KeyFactories.RSA_PRIVATE.getKey(privateKey);
|
||||
case "ec":
|
||||
return KeyFactories.EC.getKey(privateKey);
|
||||
case "rsa":
|
||||
return KeyFactories.RSA_PRIVATE.getKey(privateKey);
|
||||
case "ec":
|
||||
return KeyFactories.EC.getKey(privateKey);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(
|
||||
|
||||
@@ -318,32 +318,33 @@ class DerParser {
|
||||
|
||||
switch (this.type) {
|
||||
|
||||
// Not all are ISO-8859-1 but it's the closest thing
|
||||
case NUMERIC_STRING:
|
||||
case PRINTABLE_STRING:
|
||||
case VIDEOTEX_STRING:
|
||||
case IA5_STRING:
|
||||
case GRAPHIC_STRING:
|
||||
case ISO646_STRING:
|
||||
case GENERAL_STRING:
|
||||
encoding = "ISO-8859-1";
|
||||
break;
|
||||
// Not all are ISO-8859-1 but it's the closest thing
|
||||
case NUMERIC_STRING:
|
||||
case PRINTABLE_STRING:
|
||||
case VIDEOTEX_STRING:
|
||||
case IA5_STRING:
|
||||
case GRAPHIC_STRING:
|
||||
case ISO646_STRING:
|
||||
case GENERAL_STRING:
|
||||
encoding = "ISO-8859-1";
|
||||
break;
|
||||
|
||||
case BMP_STRING:
|
||||
encoding = "UTF-16BE";
|
||||
break;
|
||||
case BMP_STRING:
|
||||
encoding = "UTF-16BE";
|
||||
break;
|
||||
|
||||
case UTF8_STRING:
|
||||
encoding = "UTF-8";
|
||||
break;
|
||||
case UTF8_STRING:
|
||||
encoding = "UTF-8";
|
||||
break;
|
||||
|
||||
case UNIVERSAL_STRING:
|
||||
throw new IllegalStateException("Invalid DER: can't handle UCS-4 string");
|
||||
case UNIVERSAL_STRING:
|
||||
throw new IllegalStateException("Invalid DER: can't handle UCS-4 string");
|
||||
|
||||
case OID:
|
||||
return getObjectIdentifier(this.value);
|
||||
default:
|
||||
throw new IllegalStateException(String.format("Invalid DER: object (%d) is not a string", this.type));
|
||||
case OID:
|
||||
return getObjectIdentifier(this.value);
|
||||
default:
|
||||
throw new IllegalStateException(
|
||||
String.format("Invalid DER: object (%d) is not a string", this.type));
|
||||
}
|
||||
|
||||
return new String(this.value, encoding);
|
||||
|
||||
@@ -67,30 +67,30 @@ public class DurationParser {
|
||||
String typ = matcher.group(2);
|
||||
|
||||
switch (typ) {
|
||||
case "ns":
|
||||
result = result.plus(Duration.ofNanos(num));
|
||||
break;
|
||||
case "us":
|
||||
result = result.plus(Duration.ofNanos(num * 1000));
|
||||
break;
|
||||
case "ms":
|
||||
result = result.plus(Duration.ofMillis(num));
|
||||
break;
|
||||
case "s":
|
||||
result = result.plus(Duration.ofSeconds(num));
|
||||
break;
|
||||
case "m":
|
||||
result = result.plus(Duration.ofMinutes(num));
|
||||
break;
|
||||
case "h":
|
||||
result = result.plus(Duration.ofHours(num));
|
||||
break;
|
||||
case "d":
|
||||
result = result.plus(Duration.ofDays(num));
|
||||
break;
|
||||
case "w":
|
||||
result = result.plus(Duration.ofDays(num * 7));
|
||||
break;
|
||||
case "ns":
|
||||
result = result.plus(Duration.ofNanos(num));
|
||||
break;
|
||||
case "us":
|
||||
result = result.plus(Duration.ofNanos(num * 1000));
|
||||
break;
|
||||
case "ms":
|
||||
result = result.plus(Duration.ofMillis(num));
|
||||
break;
|
||||
case "s":
|
||||
result = result.plus(Duration.ofSeconds(num));
|
||||
break;
|
||||
case "m":
|
||||
result = result.plus(Duration.ofMinutes(num));
|
||||
break;
|
||||
case "h":
|
||||
result = result.plus(Duration.ofHours(num));
|
||||
break;
|
||||
case "d":
|
||||
result = result.plus(Duration.ofDays(num));
|
||||
break;
|
||||
case "w":
|
||||
result = result.plus(Duration.ofDays(num * 7));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -137,8 +137,9 @@ class KeystoreUtil {
|
||||
|
||||
List<X509Certificate> certificates = getCertificates(CERTIFICATE_FACTORY, source);
|
||||
|
||||
return certificates.stream().findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509Certificate found"));
|
||||
return certificates.stream()
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("No X509Certificate found"));
|
||||
}
|
||||
|
||||
static List<X509Certificate> getCertificates(byte[] source) throws CertificateException {
|
||||
|
||||
@@ -79,8 +79,10 @@ public class PemObject {
|
||||
*/
|
||||
public static PemObject fromKey(String content) {
|
||||
|
||||
return parse(content).stream().filter(PemObject::isPrivateKey).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Could not find a PKCS #8 private key"));
|
||||
return parse(content).stream()
|
||||
.filter(PemObject::isPrivateKey)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Could not find a PKCS #8 private key"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -276,14 +278,12 @@ public class PemObject {
|
||||
|
||||
enum PemObjectType {
|
||||
|
||||
CERTIFICATE_REQUEST("CERTIFICATE REQUEST"), NEW_CERTIFICATE_REQUEST("NEW CERTIFICATE REQUEST"), CERTIFICATE(
|
||||
"CERTIFICATE"), TRUSTED_CERTIFICATE("TRUSTED CERTIFICATE"), X509_CERTIFICATE(
|
||||
"X509 CERTIFICATE"), X509_CRL("X509 CRL"), PKCS7("PKCS7"), CMS("CMS"), ATTRIBUTE_CERTIFICATE(
|
||||
"ATTRIBUTE CERTIFICATE"), EC_PARAMETERS(
|
||||
"EC PARAMETERS"), PUBLIC_KEY("PUBLIC KEY"), RSA_PUBLIC_KEY(
|
||||
"RSA PUBLIC KEY"), RSA_PRIVATE_KEY("RSA PRIVATE KEY"), EC_PRIVATE_KEY(
|
||||
"EC PRIVATE KEY"), ENCRYPTED_PRIVATE_KEY(
|
||||
"ENCRYPTED PRIVATE KEY"), PRIVATE_KEY("PRIVATE KEY");
|
||||
CERTIFICATE_REQUEST("CERTIFICATE REQUEST"), NEW_CERTIFICATE_REQUEST("NEW CERTIFICATE REQUEST"),
|
||||
CERTIFICATE("CERTIFICATE"), TRUSTED_CERTIFICATE("TRUSTED CERTIFICATE"), X509_CERTIFICATE("X509 CERTIFICATE"),
|
||||
X509_CRL("X509 CRL"), PKCS7("PKCS7"), CMS("CMS"), ATTRIBUTE_CERTIFICATE("ATTRIBUTE CERTIFICATE"),
|
||||
EC_PARAMETERS("EC PARAMETERS"), PUBLIC_KEY("PUBLIC KEY"), RSA_PUBLIC_KEY("RSA PUBLIC KEY"),
|
||||
RSA_PRIVATE_KEY("RSA PRIVATE KEY"), EC_PRIVATE_KEY("EC PRIVATE KEY"),
|
||||
ENCRYPTED_PRIVATE_KEY("ENCRYPTED PRIVATE KEY"), PRIVATE_KEY("PRIVATE KEY");
|
||||
|
||||
// cache
|
||||
private static final PemObjectType[] constants = values();
|
||||
|
||||
@@ -481,14 +481,14 @@ public class Policy {
|
||||
|
||||
List<Capability> capabilities;
|
||||
switch (this.capabilities.size()) {
|
||||
case 0:
|
||||
capabilities = Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
capabilities = Collections.singletonList(this.capabilities.iterator().next());
|
||||
break;
|
||||
default:
|
||||
capabilities = Collections.unmodifiableList(new ArrayList<>(this.capabilities));
|
||||
case 0:
|
||||
capabilities = Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
capabilities = Collections.singletonList(this.capabilities.iterator().next());
|
||||
break;
|
||||
default:
|
||||
capabilities = Collections.unmodifiableList(new ArrayList<>(this.capabilities));
|
||||
}
|
||||
|
||||
return new Rule(this.path, capabilities, this.minWrappingTtl, this.maxWrappingTtl,
|
||||
|
||||
@@ -398,50 +398,51 @@ public class VaultCertificateRequest {
|
||||
|
||||
List<String> altNames;
|
||||
switch (this.altNames.size()) {
|
||||
case 0:
|
||||
altNames = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
altNames = java.util.Collections.singletonList(this.altNames.get(0));
|
||||
break;
|
||||
default:
|
||||
altNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.altNames));
|
||||
case 0:
|
||||
altNames = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
altNames = java.util.Collections.singletonList(this.altNames.get(0));
|
||||
break;
|
||||
default:
|
||||
altNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.altNames));
|
||||
}
|
||||
|
||||
List<String> ipSubjectAltNames;
|
||||
switch (this.ipSubjectAltNames.size()) {
|
||||
case 0:
|
||||
ipSubjectAltNames = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
ipSubjectAltNames = java.util.Collections.singletonList(this.ipSubjectAltNames.get(0));
|
||||
break;
|
||||
default:
|
||||
ipSubjectAltNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.ipSubjectAltNames));
|
||||
case 0:
|
||||
ipSubjectAltNames = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
ipSubjectAltNames = java.util.Collections.singletonList(this.ipSubjectAltNames.get(0));
|
||||
break;
|
||||
default:
|
||||
ipSubjectAltNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.ipSubjectAltNames));
|
||||
}
|
||||
|
||||
List<String> uriSubjectAltNames;
|
||||
switch (this.uriSubjectAltNames.size()) {
|
||||
case 0:
|
||||
uriSubjectAltNames = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
uriSubjectAltNames = java.util.Collections.singletonList(this.uriSubjectAltNames.get(0));
|
||||
break;
|
||||
default:
|
||||
uriSubjectAltNames = java.util.Collections.unmodifiableList(new ArrayList<>(this.uriSubjectAltNames));
|
||||
case 0:
|
||||
uriSubjectAltNames = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
uriSubjectAltNames = java.util.Collections.singletonList(this.uriSubjectAltNames.get(0));
|
||||
break;
|
||||
default:
|
||||
uriSubjectAltNames = java.util.Collections
|
||||
.unmodifiableList(new ArrayList<>(this.uriSubjectAltNames));
|
||||
}
|
||||
|
||||
List<String> otherSans;
|
||||
switch (this.otherSans.size()) {
|
||||
case 0:
|
||||
otherSans = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
otherSans = java.util.Collections.singletonList(this.otherSans.get(0));
|
||||
break;
|
||||
default:
|
||||
otherSans = java.util.Collections.unmodifiableList(new ArrayList<>(this.otherSans));
|
||||
case 0:
|
||||
otherSans = java.util.Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
otherSans = java.util.Collections.singletonList(this.otherSans.get(0));
|
||||
break;
|
||||
default:
|
||||
otherSans = java.util.Collections.unmodifiableList(new ArrayList<>(this.otherSans));
|
||||
}
|
||||
|
||||
return new VaultCertificateRequest(this.commonName, altNames, ipSubjectAltNames, uriSubjectAltNames,
|
||||
|
||||
@@ -45,7 +45,7 @@ public class VaultMetadataRequest {
|
||||
this.maxVersions = maxVersions;
|
||||
this.casRequired = casRequired;
|
||||
this.deleteVersionAfter = DurationParser
|
||||
.formatDuration(deleteVersionAfter != null ? deleteVersionAfter : Duration.ZERO);
|
||||
.formatDuration(deleteVersionAfter != null ? deleteVersionAfter : Duration.ZERO);
|
||||
}
|
||||
|
||||
public static VaultMetadataRequestBuilder builder() {
|
||||
|
||||
@@ -406,23 +406,23 @@ public class VaultTokenRequest {
|
||||
|
||||
List<String> policies;
|
||||
switch (this.policies.size()) {
|
||||
case 0:
|
||||
policies = Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
policies = Collections.singletonList(this.policies.get(0));
|
||||
break;
|
||||
default:
|
||||
policies = Collections.unmodifiableList(new ArrayList<>(this.policies));
|
||||
case 0:
|
||||
policies = Collections.emptyList();
|
||||
break;
|
||||
case 1:
|
||||
policies = Collections.singletonList(this.policies.get(0));
|
||||
break;
|
||||
default:
|
||||
policies = Collections.unmodifiableList(new ArrayList<>(this.policies));
|
||||
|
||||
}
|
||||
Map<String, String> meta;
|
||||
switch (this.meta.size()) {
|
||||
case 0:
|
||||
meta = Collections.emptyMap();
|
||||
break;
|
||||
default:
|
||||
meta = Collections.unmodifiableMap(new LinkedHashMap<>(this.meta));
|
||||
case 0:
|
||||
meta = Collections.emptyMap();
|
||||
break;
|
||||
default:
|
||||
meta = Collections.unmodifiableMap(new LinkedHashMap<>(this.meta));
|
||||
}
|
||||
|
||||
return new VaultTokenRequest(this.id, policies, meta, this.noParent, this.noDefaultPolicy, this.renewable,
|
||||
|
||||
@@ -89,7 +89,7 @@ class LeaseAwareVaultPropertySourceIntegrationTests {
|
||||
}
|
||||
catch (Exception e) {
|
||||
assertThat(e).hasRootCauseInstanceOf(VaultPropertySourceNotFoundException.class)
|
||||
.hasRootCauseMessage("Vault location [unknown] not resolvable");
|
||||
.hasRootCauseMessage("Vault location [unknown] not resolvable");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ class LeaseAwareVaultPropertySourceIntegrationTests {
|
||||
}
|
||||
catch (Exception e) {
|
||||
assertThat(e).hasRootCauseInstanceOf(VaultPropertySourceNotFoundException.class)
|
||||
.hasRootCauseMessage("Vault location [unknown] not resolvable");
|
||||
.hasRootCauseMessage("Vault location [unknown] not resolvable");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,9 +36,10 @@ class AppIdAuthenticationIntegrationTests extends AppIdAuthenticationIntegration
|
||||
@Test
|
||||
void shouldLoginSuccessfully() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("myapp") //
|
||||
.userIdMechanism(new StaticUserId("static-userid-value")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("myapp") //
|
||||
.userIdMechanism(new StaticUserId("static-userid-value")) //
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
@@ -51,14 +52,15 @@ class AppIdAuthenticationIntegrationTests extends AppIdAuthenticationIntegration
|
||||
@Test
|
||||
void loginShouldFail() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("wrong") //
|
||||
.userIdMechanism(new StaticUserId("wrong")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("wrong") //
|
||||
.userIdMechanism(new StaticUserId("wrong")) //
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new AppIdAuthentication(options, restTemplate).login());
|
||||
.isThrownBy(() -> new AppIdAuthentication(options, restTemplate).login());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -35,33 +35,35 @@ class AppIdAuthenticationOperatorIntegrationTests extends AppIdAuthenticationInt
|
||||
@Test
|
||||
void authenticationStepsShouldLoginSuccessfully() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("myapp") //
|
||||
.userIdMechanism(new StaticUserId("static-userid-value")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("myapp") //
|
||||
.userIdMechanism(new StaticUserId("static-userid-value")) //
|
||||
.build();
|
||||
|
||||
AuthenticationStepsOperator supplier = new AuthenticationStepsOperator(
|
||||
AppIdAuthentication.createAuthenticationSteps(options), this.webClient);
|
||||
|
||||
supplier.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void authenticationStepsLoginShouldFail() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("wrong") //
|
||||
.userIdMechanism(new StaticUserId("wrong")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("wrong") //
|
||||
.userIdMechanism(new StaticUserId("wrong")) //
|
||||
.build();
|
||||
|
||||
AuthenticationStepsOperator supplier = new AuthenticationStepsOperator(
|
||||
AppIdAuthentication.createAuthenticationSteps(options), this.webClient);
|
||||
|
||||
supplier.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectError() //
|
||||
.verify();
|
||||
.as(StepVerifier::create) //
|
||||
.expectError() //
|
||||
.verify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -37,9 +37,10 @@ class AppIdAuthenticationStepsIntegrationTests extends AppIdAuthenticationIntegr
|
||||
@Test
|
||||
void authenticationStepsShouldLoginSuccessfully() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("myapp") //
|
||||
.userIdMechanism(new StaticUserId("static-userid-value")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("myapp") //
|
||||
.userIdMechanism(new StaticUserId("static-userid-value")) //
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
@@ -54,9 +55,10 @@ class AppIdAuthenticationStepsIntegrationTests extends AppIdAuthenticationIntegr
|
||||
@Test
|
||||
void authenticationStepsLoginShouldFail() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("wrong") //
|
||||
.userIdMechanism(new StaticUserId("wrong")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("wrong") //
|
||||
.userIdMechanism(new StaticUserId("wrong")) //
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
|
||||
@@ -57,14 +57,17 @@ class AppIdAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainTokenWithStaticUserId() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("hello") //
|
||||
.userIdMechanism(new StaticUserId("world")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("hello") //
|
||||
.userIdMechanism(new StaticUserId("world")) //
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/app-id/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.app_id").value("hello")).andExpect(jsonPath("$.user_id").value("world"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/app-id/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.app_id").value("hello"))
|
||||
.andExpect(jsonPath("$.user_id").value("world"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
|
||||
AppIdAuthentication authentication = new AppIdAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -76,15 +79,16 @@ class AppIdAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldFail() {
|
||||
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder().appId("hello") //
|
||||
.userIdMechanism(new StaticUserId("world")) //
|
||||
.build();
|
||||
AppIdAuthenticationOptions options = AppIdAuthenticationOptions.builder()
|
||||
.appId("hello") //
|
||||
.userIdMechanism(new StaticUserId("world")) //
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/app-id/login")) //
|
||||
.andRespond(withServerError());
|
||||
.andRespond(withServerError());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new AppIdAuthentication(options, this.restTemplate).login());
|
||||
.isThrownBy(() -> new AppIdAuthentication(options, this.restTemplate).login());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -79,7 +79,8 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport {
|
||||
|
||||
String getRoleId(String roleName) {
|
||||
return (String) getVaultOperations().read(String.format("auth/approle/role/%s/role-id", roleName))
|
||||
.getRequiredData().get("role_id");
|
||||
.getRequiredData()
|
||||
.get("role_id");
|
||||
}
|
||||
|
||||
VaultToken generateWrappedSecretIdResponse() {
|
||||
@@ -88,8 +89,9 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport {
|
||||
|
||||
HttpEntity<String> httpEntity = getWrappingHeaders();
|
||||
|
||||
VaultResponse response = restOperations.exchange("auth/approle/role/with-secret-id/secret-id",
|
||||
HttpMethod.PUT, httpEntity, VaultResponse.class).getBody();
|
||||
VaultResponse response = restOperations
|
||||
.exchange("auth/approle/role/with-secret-id/secret-id", HttpMethod.PUT, httpEntity, VaultResponse.class)
|
||||
.getBody();
|
||||
|
||||
return VaultToken.of(response.getWrapInfo().get("token"));
|
||||
});
|
||||
@@ -101,8 +103,9 @@ class AppRoleAuthenticationIntegrationTestBase extends IntegrationTestSupport {
|
||||
|
||||
HttpEntity<String> httpEntity = getWrappingHeaders();
|
||||
|
||||
VaultResponse response = restOperations.exchange("auth/approle/role/with-secret-id/role-id", HttpMethod.GET,
|
||||
httpEntity, VaultResponse.class).getBody();
|
||||
VaultResponse response = restOperations
|
||||
.exchange("auth/approle/role/with-secret-id/role-id", HttpMethod.GET, httpEntity, VaultResponse.class)
|
||||
.getBody();
|
||||
|
||||
return VaultToken.of(response.getWrapInfo().get("token"));
|
||||
});
|
||||
|
||||
@@ -41,8 +41,9 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
void shouldAuthenticateWithRoleIdOnly() {
|
||||
|
||||
String roleId = getRoleId("no-secret-id");
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThat(authentication.login()).isNotNull();
|
||||
@@ -51,8 +52,11 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
@Test
|
||||
void shouldAuthenticateWithFullPullMode() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("with-secret-id")
|
||||
.roleId(RoleId.pull(Settings.token())).secretId(SecretId.pull(Settings.token())).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.appRole("with-secret-id")
|
||||
.roleId(RoleId.pull(Settings.token()))
|
||||
.secretId(SecretId.pull(Settings.token()))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThat(authentication.login()).isNotNull();
|
||||
@@ -62,8 +66,10 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
void shouldAuthenticateWithPullMode() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(getRoleId("with-secret-id"))).appRole("with-secret-id")
|
||||
.secretId(SecretId.pull(Settings.token())).build();
|
||||
.roleId(RoleId.provided(getRoleId("with-secret-id")))
|
||||
.appRole("with-secret-id")
|
||||
.secretId(SecretId.pull(Settings.token()))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThat(authentication.login()).isNotNull();
|
||||
@@ -74,11 +80,14 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
|
||||
String roleId = getRoleId("with-secret-id");
|
||||
String secretId = (String) getVaultOperations()
|
||||
.write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData()
|
||||
.get("secret_id");
|
||||
.write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null)
|
||||
.getRequiredData()
|
||||
.get("secret_id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided(secretId)).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided(secretId))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThat(authentication.login()).isNotNull();
|
||||
@@ -91,8 +100,10 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
VaultToken unwrappingToken = generateWrappedSecretIdResponse();
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.secretId(SecretId.wrapped(unwrappingToken)).roleId(RoleId.provided(roleId))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).build();
|
||||
.secretId(SecretId.wrapped(unwrappingToken))
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.build();
|
||||
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
@@ -106,8 +117,10 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
VaultToken roleIdToken = generateWrappedRoleIdResponse();
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.secretId(SecretId.wrapped(secretIdToken)).roleId(RoleId.wrapped(roleIdToken))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).build();
|
||||
.secretId(SecretId.wrapped(secretIdToken))
|
||||
.roleId(RoleId.wrapped(roleIdToken))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.build();
|
||||
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
@@ -121,8 +134,10 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
String unwrappingToken = "incorrect-unwrapping-token";
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.secretId(SecretId.wrapped(VaultToken.of(unwrappingToken))).roleId(RoleId.provided(roleId))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).build();
|
||||
.secretId(SecretId.wrapped(VaultToken.of(unwrappingToken)))
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.build();
|
||||
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
@@ -134,8 +149,9 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
|
||||
String roleId = getRoleId("with-secret-id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login);
|
||||
@@ -146,8 +162,10 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
|
||||
String roleId = getRoleId("with-secret-id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided("this-is-a-wrong-secret-id")).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided("this-is-a-wrong-secret-id"))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class).isThrownBy(authentication::login);
|
||||
@@ -162,8 +180,10 @@ class AppRoleAuthenticationIntegrationTests extends AppRoleAuthenticationIntegra
|
||||
VaultResponse customSecretIdResponse = getVaultOperations().write(
|
||||
"auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId));
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided(secretId)).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided(secretId))
|
||||
.build();
|
||||
AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate());
|
||||
|
||||
assertThat(authentication.login()).isNotNull();
|
||||
|
||||
@@ -42,8 +42,9 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
void shouldAuthenticateWithRoleIdOnly() {
|
||||
|
||||
String roleId = getRoleId("no-secret-id");
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -58,8 +59,10 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
VaultToken unwrappingToken = generateWrappedSecretIdResponse();
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.secretId(SecretId.wrapped(unwrappingToken)).roleId(RoleId.provided(roleId))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).build();
|
||||
.secretId(SecretId.wrapped(unwrappingToken))
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -71,14 +74,17 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
void authenticationStepsShouldAuthenticateWithWrappedRoleId() {
|
||||
|
||||
String secretId = (String) getVaultOperations()
|
||||
.write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData()
|
||||
.get("secret_id");
|
||||
.write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null)
|
||||
.getRequiredData()
|
||||
.get("secret_id");
|
||||
|
||||
VaultToken roleIdToken = generateWrappedRoleIdResponse();
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.secretId(SecretId.provided(secretId)).roleId(RoleId.wrapped(roleIdToken))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).build();
|
||||
.secretId(SecretId.provided(secretId))
|
||||
.roleId(RoleId.wrapped(roleIdToken))
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -89,8 +95,11 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
@Test
|
||||
void shouldAuthenticateWithFullPullMode() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("with-secret-id")
|
||||
.roleId(RoleId.pull(Settings.token())).secretId(SecretId.pull(Settings.token())).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.appRole("with-secret-id")
|
||||
.roleId(RoleId.pull(Settings.token()))
|
||||
.secretId(SecretId.pull(Settings.token()))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -103,8 +112,11 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
|
||||
String roleId = getRoleId("with-secret-id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("with-secret-id")
|
||||
.secretId(SecretId.pull(Settings.token())).roleId(RoleId.provided(roleId)).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.appRole("with-secret-id")
|
||||
.secretId(SecretId.pull(Settings.token()))
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -116,12 +128,15 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
void authenticationStepsShouldAuthenticateWithPullRoleId() {
|
||||
|
||||
String secretId = (String) getVaultOperations()
|
||||
.write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData()
|
||||
.get("secret_id");
|
||||
.write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null)
|
||||
.getRequiredData()
|
||||
.get("secret_id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.secretId(SecretId.provided(secretId)).appRole("with-secret-id").roleId(RoleId.pull(Settings.token()))
|
||||
.build();
|
||||
.secretId(SecretId.provided(secretId))
|
||||
.appRole("with-secret-id")
|
||||
.roleId(RoleId.pull(Settings.token()))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -134,8 +149,10 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
|
||||
String roleId = getRoleId("with-secret-id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided("this-is-a-wrong-secret-id")).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided("this-is-a-wrong-secret-id"))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -152,8 +169,10 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
VaultResponse customSecretIdResponse = getVaultOperations().write(
|
||||
"auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId));
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided(secretId)).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.secretId(SecretId.provided(secretId))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
@@ -169,8 +188,11 @@ class AppRoleAuthenticationStepsIntegrationTests extends AppRoleAuthenticationIn
|
||||
|
||||
String roleId = getRoleId("with-secret-id");
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided(roleId))
|
||||
.appRole("with-secret-id").secretId(SecretId.pull(Settings.token())).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided(roleId))
|
||||
.appRole("with-secret-id")
|
||||
.secretId(SecretId.pull(Settings.token()))
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AppRoleAuthentication.createAuthenticationSteps(options), prepare().getRestTemplate());
|
||||
|
||||
@@ -70,14 +70,17 @@ class AppRoleAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainToken() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) //
|
||||
.secretId(SecretId.provided("world")) //
|
||||
.build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided("hello")) //
|
||||
.secretId(SecretId.provided("world")) //
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("hello")).andExpect(jsonPath("$.secret_id").value("world"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("hello"))
|
||||
.andExpect(jsonPath("$.secret_id").value("world"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
|
||||
AppRoleAuthentication sut = new AppRoleAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -90,22 +93,30 @@ class AppRoleAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldPullRoleIdAndSecretId() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().appRole("app_role")
|
||||
.roleId(RoleId.pull(VaultToken.of("initial_token")))
|
||||
.secretId(SecretId.pull(VaultToken.of("initial_token"))).build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.appRole("app_role")
|
||||
.roleId(RoleId.pull(VaultToken.of("initial_token")))
|
||||
.secretId(SecretId.pull(VaultToken.of("initial_token")))
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/approle/role/app_role/role-id")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header("X-Vault-token", "initial_token")).andRespond(withSuccess()
|
||||
.contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\"role_id\": \"hello\"}}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/role/app_role/role-id"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header("X-Vault-token", "initial_token"))
|
||||
.andRespond(
|
||||
withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\"role_id\": \"hello\"}}"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/approle/role/app_role/secret-id")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(header("X-Vault-token", "initial_token")).andRespond(withSuccess()
|
||||
.contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\"secret_id\": \"world\"}}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/role/app_role/secret-id"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(header("X-Vault-token", "initial_token"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\": {\"secret_id\": \"world\"}}"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("hello")).andExpect(jsonPath("$.secret_id").value("world"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("hello"))
|
||||
.andExpect(jsonPath("$.secret_id").value("world"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
|
||||
AppRoleAuthentication sut = new AppRoleAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -123,20 +134,23 @@ class AppRoleAuthenticationUnitTests {
|
||||
@Test
|
||||
void optionsShouldRequireTokenOrRoleIdIfAppRoleIdIsSet() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> AppRoleAuthenticationOptions.builder().appRole("app_role").build());
|
||||
.isThrownBy(() -> AppRoleAuthenticationOptions.builder().appRole("app_role").build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginShouldObtainTokenWithoutSecretId() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) //
|
||||
.build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided("hello")) //
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("hello")).andExpect(jsonPath("$.secret_id").doesNotExist())
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("hello"))
|
||||
.andExpect(jsonPath("$.secret_id").doesNotExist())
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}"
|
||||
+ "}"));
|
||||
|
||||
AppRoleAuthentication sut = new AppRoleAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -151,22 +165,25 @@ class AppRoleAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldFail() {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder().roleId(RoleId.provided("hello")) //
|
||||
.build();
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided("hello")) //
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/approle/login")) //
|
||||
.andRespond(withServerError());
|
||||
.andRespond(withServerError());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new AppRoleAuthentication(options, this.restTemplate).login());
|
||||
.isThrownBy(() -> new AppRoleAuthentication(options, this.restTemplate).login());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginShouldUnwrapCubbyholeSecretIdResponse() throws Exception {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided("my_role_id")).secretId(SecretId.wrapped(VaultToken.of("unwrapping_token")))
|
||||
.unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole).build();
|
||||
.roleId(RoleId.provided("my_role_id"))
|
||||
.secretId(SecretId.wrapped(VaultToken.of("unwrapping_token")))
|
||||
.unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole)
|
||||
.build();
|
||||
|
||||
String wrappedResponse = "{" + " \"request_id\": \"aad6a19b-a42b-b750-cafb-51087662f53e\","
|
||||
+ " \"lease_id\": \"\"," + " \"renewable\": false," + " \"lease_duration\": 0," + " \"data\": {"
|
||||
@@ -174,18 +191,20 @@ class AppRoleAuthenticationUnitTests {
|
||||
+ " }," + " \"wrap_info\": null," + " \"warnings\": null," + " \"auth\": null" + "}";
|
||||
|
||||
// Expect a first request to unwrap the response
|
||||
this.mockRest.expect(requestTo("/cubbyhole/response")).andExpect(header("X-Vault-Token", "unwrapping_token"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }"));
|
||||
this.mockRest.expect(requestTo("/cubbyhole/response"))
|
||||
.andExpect(header("X-Vault-Token", "unwrapping_token"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }"));
|
||||
|
||||
// Also expect a second request to retrieve a token
|
||||
this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("my_role_id"))
|
||||
.andExpect(jsonPath("$.secret_id").value("my_secret_id"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("my_role_id"))
|
||||
.andExpect(jsonPath("$.secret_id").value("my_secret_id"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}"
|
||||
+ "}"));
|
||||
|
||||
AppRoleAuthentication auth = new AppRoleAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -201,8 +220,9 @@ class AppRoleAuthenticationUnitTests {
|
||||
void loginShouldUnwrapSecretIdResponse() throws Exception {
|
||||
|
||||
AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder()
|
||||
.roleId(RoleId.provided("my_role_id")).secretId(SecretId.wrapped(VaultToken.of("unwrapping_token")))
|
||||
.build();
|
||||
.roleId(RoleId.provided("my_role_id"))
|
||||
.secretId(SecretId.wrapped(VaultToken.of("unwrapping_token")))
|
||||
.build();
|
||||
|
||||
String wrappedResponse = "{" + " \"request_id\": \"aad6a19b-a42b-b750-cafb-51087662f53e\","
|
||||
+ " \"lease_id\": \"\"," + " \"renewable\": false," + " \"lease_duration\": 0," + " \"data\": {"
|
||||
@@ -210,17 +230,19 @@ class AppRoleAuthenticationUnitTests {
|
||||
+ " }," + " \"wrap_info\": null," + " \"warnings\": null," + " \"auth\": null" + "}";
|
||||
|
||||
// Expect a first request to unwrap the response
|
||||
this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(header("X-Vault-Token", "unwrapping_token"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));
|
||||
this.mockRest.expect(requestTo("/sys/wrapping/unwrap"))
|
||||
.andExpect(header("X-Vault-Token", "unwrapping_token"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));
|
||||
|
||||
// Also expect a second request to retrieve a token
|
||||
this.mockRest.expect(requestTo("/auth/approle/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("my_role_id"))
|
||||
.andExpect(jsonPath("$.secret_id").value("my_secret_id"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/approle/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role_id").value("my_role_id"))
|
||||
.andExpect(jsonPath("$.secret_id").value("my_secret_id"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\": 10, \"renewable\": true}"
|
||||
+ "}"));
|
||||
|
||||
AppRoleAuthentication auth = new AppRoleAuthentication(options, this.restTemplate);
|
||||
|
||||
|
||||
@@ -85,8 +85,8 @@ class AuthenticationStepsExecutorUnitTests {
|
||||
void fileResourceCredentialSupplierShouldBeLoaded() {
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ClassPathResource("kube-jwt-token")))
|
||||
.login(VaultToken::of);
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ClassPathResource("kube-jwt-token")))
|
||||
.login(VaultToken::of);
|
||||
|
||||
assertThat(login(steps).getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
}
|
||||
@@ -95,8 +95,8 @@ class AuthenticationStepsExecutorUnitTests {
|
||||
void inputStreamResourceCredentialSupplierShouldBeLoaded() {
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ByteArrayResource("eyJhbGciOiJSUz".getBytes())))
|
||||
.login(VaultToken::of);
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ByteArrayResource("eyJhbGciOiJSUz".getBytes())))
|
||||
.login(VaultToken::of);
|
||||
|
||||
assertThat(login(steps).getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
}
|
||||
@@ -104,13 +104,14 @@ class AuthenticationStepsExecutorUnitTests {
|
||||
@Test
|
||||
void justLoginRequestShouldLogin() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/cert/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
|
||||
assertThat(login(steps)).isEqualTo(VaultToken.of("my-token"));
|
||||
}
|
||||
@@ -118,33 +119,38 @@ class AuthenticationStepsExecutorUnitTests {
|
||||
@Test
|
||||
void justLoginShouldFail() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withBadRequest().body("foo"));
|
||||
this.mockRest.expect(requestTo("/auth/cert/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withBadRequest().body("foo"));
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
|
||||
assertThatExceptionOfType(VaultException.class).isThrownBy(() -> login(steps)).withMessageContaining(
|
||||
"HTTP request POST /auth/{path}/login AS class org.springframework.vault.support.VaultResponse "
|
||||
+ "in state null failed with Status 400 and body foo");
|
||||
assertThatExceptionOfType(VaultException.class).isThrownBy(() -> login(steps))
|
||||
.withMessageContaining(
|
||||
"HTTP request POST /auth/{path}/login AS class org.springframework.vault.support.VaultResponse "
|
||||
+ "in state null failed with Status 400 and body foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
void initialRequestWithMapShouldLogin() {
|
||||
|
||||
this.mockRest.expect(requestTo("somewhere/else")).andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo"));
|
||||
this.mockRest.expect(requestTo("somewhere/else"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(content().string("foo-token"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/cert/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(content().string("foo-token"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromHttpRequest(get(URI.create("somewhere/else")).as(String.class)).onNext(System.out::println) //
|
||||
.map(s -> s.concat("-token")) //
|
||||
.login("/auth/cert/login");
|
||||
.fromHttpRequest(get(URI.create("somewhere/else")).as(String.class))
|
||||
.onNext(System.out::println) //
|
||||
.map(s -> s.concat("-token")) //
|
||||
.login("/auth/cert/login");
|
||||
|
||||
assertThat(login(steps)).isEqualTo(VaultToken.of("foo-token"));
|
||||
}
|
||||
@@ -153,21 +159,22 @@ class AuthenticationStepsExecutorUnitTests {
|
||||
void requestWithHeadersShouldLogin() {
|
||||
|
||||
this.mockRest.expect(requestTo("somewhere/else")) //
|
||||
.andExpect(header("foo", "bar")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo"));
|
||||
.andExpect(header("foo", "bar")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("foo"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/cert/login")).andExpect(content().string("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/cert/login"))
|
||||
.andExpect(content().string("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"foo-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("foo", "bar");
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromHttpRequest(get(URI.create("somewhere/else")).with(headers).as(String.class)) //
|
||||
.login("/auth/cert/login");
|
||||
.fromHttpRequest(get(URI.create("somewhere/else")).with(headers).as(String.class)) //
|
||||
.login("/auth/cert/login");
|
||||
|
||||
assertThat(login(steps)).isEqualTo(VaultToken.of("foo-token"));
|
||||
}
|
||||
@@ -175,20 +182,22 @@ class AuthenticationStepsExecutorUnitTests {
|
||||
@Test
|
||||
void zipWithShouldRequestTwoItems() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/login/left")).andExpect(method(HttpMethod.POST)).andRespond(
|
||||
withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"left\"}"));
|
||||
this.mockRest.expect(requestTo("/auth/login/left"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"left\"}"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/login/right")).andExpect(method(HttpMethod.POST)).andRespond(
|
||||
withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"right\"}"));
|
||||
this.mockRest.expect(requestTo("/auth/login/right"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"request_id\": \"right\"}"));
|
||||
|
||||
Node<VaultResponse> left = AuthenticationSteps
|
||||
.fromHttpRequest(post("/auth/login/left").as(VaultResponse.class));
|
||||
.fromHttpRequest(post("/auth/login/left").as(VaultResponse.class));
|
||||
|
||||
Node<VaultResponse> right = AuthenticationSteps
|
||||
.fromHttpRequest(post("/auth/login/right").as(VaultResponse.class));
|
||||
.fromHttpRequest(post("/auth/login/right").as(VaultResponse.class));
|
||||
|
||||
AuthenticationSteps steps = left.zipWith(right)
|
||||
.login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId()));
|
||||
.login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId()));
|
||||
|
||||
assertThat(login(steps)).isEqualTo(VaultToken.of("left-right"));
|
||||
}
|
||||
|
||||
@@ -53,8 +53,8 @@ class AuthenticationStepsOperatorUnitTests {
|
||||
AuthenticationSteps steps = AuthenticationSteps.just(VaultToken.of("my-token"));
|
||||
|
||||
login(steps).as(StepVerifier::create) //
|
||||
.expectNext(VaultToken.of("my-token")) //
|
||||
.verifyComplete();
|
||||
.expectNext(VaultToken.of("my-token")) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,49 +63,52 @@ class AuthenticationStepsOperatorUnitTests {
|
||||
AuthenticationSteps steps = AuthenticationSteps.fromSupplier(() -> "my-token").login(VaultToken::of);
|
||||
|
||||
login(steps).as(StepVerifier::create) //
|
||||
.expectNext(VaultToken.of("my-token")) //
|
||||
.verifyComplete();
|
||||
.expectNext(VaultToken.of("my-token")) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fileResourceCredentialSupplierShouldBeLoaded() {
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ClassPathResource("kube-jwt-token")))
|
||||
.login(VaultToken::of);
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ClassPathResource("kube-jwt-token")))
|
||||
.login(VaultToken::of);
|
||||
|
||||
login(steps).as(StepVerifier::create) //
|
||||
.consumeNextWith(actual -> {
|
||||
assertThat(actual.getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
}).verifyComplete();
|
||||
.consumeNextWith(actual -> {
|
||||
assertThat(actual.getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentFileResourceCredentialSupplierShouldFail() {
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ByteArrayResource("eyJhbGciOiJSUz".getBytes()) {
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
throw new IOException("Oops!");
|
||||
}
|
||||
})).login(VaultToken::of);
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ByteArrayResource("eyJhbGciOiJSUz".getBytes()) {
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
throw new IOException("Oops!");
|
||||
}
|
||||
}))
|
||||
.login(VaultToken::of);
|
||||
|
||||
login(steps).as(StepVerifier::create) //
|
||||
.verifyError(VaultException.class);
|
||||
.verifyError(VaultException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputStreamResourceCredentialSupplierShouldBeLoaded() {
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ByteArrayResource("eyJhbGciOiJSUz".getBytes())))
|
||||
.login(VaultToken::of);
|
||||
.fromSupplier(new ResourceCredentialSupplier(new ByteArrayResource("eyJhbGciOiJSUz".getBytes())))
|
||||
.login(VaultToken::of);
|
||||
|
||||
login(steps).as(StepVerifier::create) //
|
||||
.consumeNextWith(actual -> {
|
||||
assertThat(actual.getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
}).verifyComplete();
|
||||
.consumeNextWith(actual -> {
|
||||
assertThat(actual.getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,9 +117,10 @@ class AuthenticationStepsOperatorUnitTests {
|
||||
AuthenticationSteps steps = AuthenticationSteps.fromSupplier(() -> "eyJhbGciOiJSUz").login(VaultToken::of);
|
||||
|
||||
login(steps).as(StepVerifier::create) //
|
||||
.consumeNextWith(actual -> {
|
||||
assertThat(actual.getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
}).verifyComplete();
|
||||
.consumeNextWith(actual -> {
|
||||
assertThat(actual.getToken()).startsWith("eyJhbGciOiJSUz");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,11 +136,11 @@ class AuthenticationStepsOperatorUnitTests {
|
||||
WebClient webClient = WebClient.builder().clientConnector(connector).build();
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
|
||||
login(steps, webClient).as(StepVerifier::create) //
|
||||
.expectNext(VaultToken.of("my-token")) //
|
||||
.verifyComplete();
|
||||
.expectNext(VaultToken.of("my-token")) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -149,11 +153,11 @@ class AuthenticationStepsOperatorUnitTests {
|
||||
WebClient webClient = WebClient.builder().clientConnector(connector).build();
|
||||
|
||||
AuthenticationSteps steps = AuthenticationSteps
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
.just(post("/auth/{path}/login", "cert").as(VaultResponse.class));
|
||||
|
||||
login(steps, webClient).as(StepVerifier::create) //
|
||||
.expectError() //
|
||||
.verify();
|
||||
.expectError() //
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -181,17 +185,17 @@ class AuthenticationStepsOperatorUnitTests {
|
||||
WebClient webClient = WebClient.builder().clientConnector(connector).build();
|
||||
|
||||
Node<VaultResponse> left = AuthenticationSteps
|
||||
.fromHttpRequest(post("/auth/login/left").as(VaultResponse.class));
|
||||
.fromHttpRequest(post("/auth/login/left").as(VaultResponse.class));
|
||||
|
||||
Node<VaultResponse> right = AuthenticationSteps
|
||||
.fromHttpRequest(post("/auth/login/right").as(VaultResponse.class));
|
||||
.fromHttpRequest(post("/auth/login/right").as(VaultResponse.class));
|
||||
|
||||
AuthenticationSteps steps = left.zipWith(right)
|
||||
.login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId()));
|
||||
.login(it -> VaultToken.of(it.getLeft().getRequestId() + "-" + it.getRight().getRequestId()));
|
||||
|
||||
login(steps, webClient).as(StepVerifier::create) //
|
||||
.expectNext(VaultToken.of("left-right")) //
|
||||
.verifyComplete();
|
||||
.expectNext(VaultToken.of("left-right")) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
private Mono<VaultToken> login(AuthenticationSteps steps) {
|
||||
|
||||
@@ -64,8 +64,8 @@ class AwsEc2AuthenticationUnitTests {
|
||||
void shouldObtainIdentityDocument() {
|
||||
|
||||
this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("Hello, world"));
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("Hello, world"));
|
||||
|
||||
AwsEc2Authentication authentication = new AwsEc2Authentication(this.restTemplate);
|
||||
|
||||
@@ -76,8 +76,8 @@ class AwsEc2AuthenticationUnitTests {
|
||||
void shouldCleanUpIdentityResponse() {
|
||||
|
||||
this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("Hello, \r\r\n\nworld"));
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("Hello, \r\r\n\nworld"));
|
||||
|
||||
AwsEc2Authentication authentication = new AwsEc2Authentication(this.restTemplate);
|
||||
|
||||
@@ -90,15 +90,16 @@ class AwsEc2AuthenticationUnitTests {
|
||||
AwsEc2AuthenticationOptions options = AwsEc2AuthenticationOptions.builder().role("ami").build();
|
||||
|
||||
this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("Hello, world"));
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("Hello, world"));
|
||||
|
||||
AwsEc2Authentication authentication = new AwsEc2Authentication(options, this.restTemplate, this.restTemplate);
|
||||
|
||||
assertThat(authentication.getEc2Login()) //
|
||||
.containsEntry("pkcs7", "Hello, world") //
|
||||
.containsEntry("role", "ami") //
|
||||
.containsKey("nonce").hasSize(3);
|
||||
.containsEntry("pkcs7", "Hello, world") //
|
||||
.containsEntry("role", "ami") //
|
||||
.containsKey("nonce")
|
||||
.hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,13 +110,15 @@ class AwsEc2AuthenticationUnitTests {
|
||||
AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions.builder().nonce(nonce).build();
|
||||
|
||||
this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("value"));
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("value"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/aws-ec2/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.pkcs7").value("value")).andExpect(jsonPath("$.nonce").value("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/aws-ec2/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.pkcs7").value("value"))
|
||||
.andExpect(jsonPath("$.nonce").value("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}"));
|
||||
|
||||
AwsEc2Authentication authentication = new AwsEc2Authentication(authenticationOptions, this.restTemplate,
|
||||
this.restTemplate);
|
||||
@@ -136,13 +139,15 @@ class AwsEc2AuthenticationUnitTests {
|
||||
AwsEc2AuthenticationOptions options = AwsEc2AuthenticationOptions.builder().nonce(nonce).build();
|
||||
|
||||
this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("value"));
|
||||
.andExpect(method(HttpMethod.GET)) //
|
||||
.andRespond(withSuccess().body("value"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/aws-ec2/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.pkcs7").value("value")).andExpect(jsonPath("$.nonce").value("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/aws-ec2/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.pkcs7").value("value"))
|
||||
.andExpect(jsonPath("$.nonce").value("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"lease_duration\":20}" + "}"));
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
AwsEc2Authentication.createAuthenticationSteps(options), this.restTemplate);
|
||||
@@ -158,17 +163,17 @@ class AwsEc2AuthenticationUnitTests {
|
||||
void loginShouldFailWhileObtainingIdentityDocument() {
|
||||
|
||||
this.mockRest.expect(requestTo("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")) //
|
||||
.andRespond(withServerError());
|
||||
.andRespond(withServerError());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new AwsEc2Authentication(this.restTemplate).login());
|
||||
.isThrownBy(() -> new AwsEc2Authentication(this.restTemplate).login());
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginShouldFail() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/aws-ec2/login")) //
|
||||
.andRespond(withServerError());
|
||||
.andRespond(withServerError());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class).isThrownBy(() -> new AwsEc2Authentication(this.restTemplate) {
|
||||
@Override
|
||||
|
||||
@@ -57,16 +57,22 @@ class AwsIamAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldAuthenticate() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.iam_http_request_method").value("POST"))
|
||||
.andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists())
|
||||
.andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/aws/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.iam_http_request_method").value("POST"))
|
||||
.andExpect(jsonPath("$.iam_request_url").exists())
|
||||
.andExpect(jsonPath("$.iam_request_body").exists())
|
||||
.andExpect(jsonPath("$.iam_request_headers").exists())
|
||||
.andExpect(jsonPath("$.role").value("foo-role"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role")
|
||||
.regionProvider(() -> Region.US_WEST_1).credentials(AwsBasicCredentials.create("foo", "bar")).build();
|
||||
AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder()
|
||||
.role("foo-role")
|
||||
.regionProvider(() -> Region.US_WEST_1)
|
||||
.credentials(AwsBasicCredentials.create("foo", "bar"))
|
||||
.build();
|
||||
AwsIamAuthentication sut = new AwsIamAuthentication(options, this.restTemplate);
|
||||
|
||||
VaultToken login = sut.login();
|
||||
@@ -80,16 +86,22 @@ class AwsIamAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldUsingAuthenticationSteps() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.iam_http_request_method").value("POST"))
|
||||
.andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists())
|
||||
.andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/aws/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.iam_http_request_method").value("POST"))
|
||||
.andExpect(jsonPath("$.iam_request_url").exists())
|
||||
.andExpect(jsonPath("$.iam_request_body").exists())
|
||||
.andExpect(jsonPath("$.iam_request_headers").exists())
|
||||
.andExpect(jsonPath("$.role").value("foo-role"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role")
|
||||
.region(Region.US_WEST_1).credentials(AwsBasicCredentials.create("foo", "bar")).build();
|
||||
AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder()
|
||||
.role("foo-role")
|
||||
.region(Region.US_WEST_1)
|
||||
.credentials(AwsBasicCredentials.create("foo", "bar"))
|
||||
.build();
|
||||
|
||||
AuthenticationSteps steps = AwsIamAuthentication.createAuthenticationSteps(options);
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(steps, this.restTemplate);
|
||||
|
||||
@@ -54,8 +54,9 @@ class AzureMsiAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainTokenAndFetchMetadata() {
|
||||
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") //
|
||||
.build();
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
|
||||
.role("dev-role") //
|
||||
.build();
|
||||
|
||||
expectVmMetadataRequest();
|
||||
expectIdentityTokenRequest();
|
||||
@@ -71,8 +72,10 @@ class AzureMsiAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainToken() {
|
||||
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role")
|
||||
.vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", "vault-client")).build();
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
|
||||
.role("dev-role")
|
||||
.vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", "vault-client"))
|
||||
.build();
|
||||
|
||||
expectIdentityTokenRequest();
|
||||
expectVmLoginRequest();
|
||||
@@ -87,8 +90,9 @@ class AzureMsiAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginWithStepsShouldObtainTokenAndFetchMetadata() {
|
||||
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") //
|
||||
.build();
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
|
||||
.role("dev-role") //
|
||||
.build();
|
||||
|
||||
expectVmMetadataRequest();
|
||||
expectIdentityTokenRequest();
|
||||
@@ -105,8 +109,10 @@ class AzureMsiAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginWithStepsShouldObtainToken() {
|
||||
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role")
|
||||
.vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", "vault-client")).build();
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
|
||||
.role("dev-role")
|
||||
.vmEnvironment(new AzureVmEnvironment("foobar-subscription", "vault", "vault-client"))
|
||||
.build();
|
||||
|
||||
expectIdentityTokenRequest();
|
||||
expectVmLoginRequest();
|
||||
@@ -122,8 +128,9 @@ class AzureMsiAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginFromScaleSetShouldObtainToken() {
|
||||
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role("dev-role") //
|
||||
.build();
|
||||
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
|
||||
.role("dev-role") //
|
||||
.build();
|
||||
|
||||
expectVmssMetadataRequest();
|
||||
expectIdentityTokenRequest();
|
||||
@@ -139,53 +146,62 @@ class AzureMsiAuthenticationUnitTests {
|
||||
private void expectVmMetadataRequest() {
|
||||
|
||||
this.mockRest.expect(requestTo(AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI))
|
||||
.andExpect(method(HttpMethod.GET)).andExpect(header("Metadata", "true"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\n" + " \"compute\": {\n" + " \"name\": \"vault-client\",\n"
|
||||
+ " \"vmScaleSetName\": \"\",\n" + " \"resourceGroupName\": \"vault\",\n"
|
||||
+ " \"subscriptionId\": \"foobar-subscription\"\n" + " }\n" + "}"));
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header("Metadata", "true"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\n" + " \"compute\": {\n" + " \"name\": \"vault-client\",\n"
|
||||
+ " \"vmScaleSetName\": \"\",\n" + " \"resourceGroupName\": \"vault\",\n"
|
||||
+ " \"subscriptionId\": \"foobar-subscription\"\n" + " }\n" + "}"));
|
||||
}
|
||||
|
||||
private void expectVmssMetadataRequest() {
|
||||
|
||||
this.mockRest.expect(requestTo(AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI))
|
||||
.andExpect(method(HttpMethod.GET)).andExpect(header("Metadata", "true"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\n" + " \"compute\": {\n" + " \"name\": \"vault-client-scale-set_0\",\n"
|
||||
+ " \"vmScaleSetName\": \"vault-client-scale-set\",\n"
|
||||
+ " \"resourceGroupName\": \"vault\",\n"
|
||||
+ " \"subscriptionId\": \"foobar-subscription\"\n" + " }\n" + "}"));
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header("Metadata", "true"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\n" + " \"compute\": {\n" + " \"name\": \"vault-client-scale-set_0\",\n"
|
||||
+ " \"vmScaleSetName\": \"vault-client-scale-set\",\n"
|
||||
+ " \"resourceGroupName\": \"vault\",\n" + " \"subscriptionId\": \"foobar-subscription\"\n"
|
||||
+ " }\n" + "}"));
|
||||
}
|
||||
|
||||
private void expectIdentityTokenRequest() {
|
||||
|
||||
this.mockRest.expect(requestTo(AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI))
|
||||
.andExpect(method(HttpMethod.GET)).andExpect(header("Metadata", "true")).andRespond(withSuccess()
|
||||
.contentType(MediaType.APPLICATION_JSON).body("{\"access_token\": \"my-token\" }"));
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header("Metadata", "true"))
|
||||
.andRespond(
|
||||
withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"access_token\": \"my-token\" }"));
|
||||
|
||||
}
|
||||
|
||||
private void expectVmLoginRequest() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/azure/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-token"))
|
||||
.andExpect(jsonPath("$.subscription_id").value("foobar-subscription"))
|
||||
.andExpect(jsonPath("$.resource_group_name").value("vault"))
|
||||
.andExpect(jsonPath("$.vm_name").value("vault-client")).andExpect(jsonPath("$.vmss_name").value(""))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/azure/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role"))
|
||||
.andExpect(jsonPath("$.jwt").value("my-token"))
|
||||
.andExpect(jsonPath("$.subscription_id").value("foobar-subscription"))
|
||||
.andExpect(jsonPath("$.resource_group_name").value("vault"))
|
||||
.andExpect(jsonPath("$.vm_name").value("vault-client"))
|
||||
.andExpect(jsonPath("$.vmss_name").value(""))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
}
|
||||
|
||||
private void expectVmssLoginRequest() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/azure/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-token"))
|
||||
.andExpect(jsonPath("$.subscription_id").value("foobar-subscription"))
|
||||
.andExpect(jsonPath("$.resource_group_name").value("vault"))
|
||||
.andExpect(jsonPath("$.vm_name").value("vault-client-scale-set_0"))
|
||||
.andExpect(jsonPath("$.vmss_name").value("vault-client-scale-set"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/azure/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role"))
|
||||
.andExpect(jsonPath("$.jwt").value("my-token"))
|
||||
.andExpect(jsonPath("$.subscription_id").value("foobar-subscription"))
|
||||
.andExpect(jsonPath("$.resource_group_name").value("vault"))
|
||||
.andExpect(jsonPath("$.vm_name").value("vault-client-scale-set_0"))
|
||||
.andExpect(jsonPath("$.vmss_name").value("vault-client-scale-set"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,9 +40,11 @@ import static org.springframework.vault.util.Settings.findWorkDir;
|
||||
*/
|
||||
public abstract class ClientCertificateAuthenticationIntegrationTestBase extends IntegrationTestSupport {
|
||||
|
||||
static final Policy POLICY = Policy
|
||||
.of(Policy.Rule.builder().path("/*").capabilities(Policy.BuiltinCapabilities.READ,
|
||||
Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE).build());
|
||||
static final Policy POLICY = Policy.of(Policy.Rule.builder()
|
||||
.path("/*")
|
||||
.capabilities(Policy.BuiltinCapabilities.READ, Policy.BuiltinCapabilities.CREATE,
|
||||
Policy.BuiltinCapabilities.UPDATE)
|
||||
.build());
|
||||
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
@@ -76,7 +78,7 @@ public abstract class ClientCertificateAuthenticationIntegrationTestBase extends
|
||||
SslConfiguration original = createSslConfiguration();
|
||||
|
||||
return new SslConfiguration(KeyStoreConfiguration
|
||||
.of(new FileSystemResource(new File(findWorkDir(), "client-cert.jks")), "changeit".toCharArray()),
|
||||
.of(new FileSystemResource(new File(findWorkDir(), "client-cert.jks")), "changeit".toCharArray()),
|
||||
keyConfiguration, original.getTrustStoreConfiguration());
|
||||
}
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ class ClientCertificateAuthenticationIntegrationTests extends ClientCertificateA
|
||||
clientHttpRequestFactory);
|
||||
|
||||
assertThatExceptionOfType(NestedRuntimeException.class)
|
||||
.isThrownBy(() -> new ClientCertificateAuthentication(restTemplate).login());
|
||||
.isThrownBy(() -> new ClientCertificateAuthentication(restTemplate).login());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,9 +42,9 @@ class ClientCertificateAuthenticationOperatorIntegrationTests
|
||||
ClientCertificateAuthentication.createAuthenticationSteps(), webClient);
|
||||
|
||||
operator.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -57,9 +57,9 @@ class ClientCertificateAuthenticationOperatorIntegrationTests
|
||||
ClientCertificateAuthentication.createAuthenticationSteps(), webClient);
|
||||
|
||||
operator.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,14 +72,14 @@ class ClientCertificateAuthenticationOperatorIntegrationTests
|
||||
ClientCertificateAuthentication.createAuthenticationSteps(), webClient);
|
||||
|
||||
operator.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.verifyError(VaultLoginException.class);
|
||||
.as(StepVerifier::create) //
|
||||
.verifyError(VaultLoginException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldProvideInvalidKeyPassword() {
|
||||
assertThatIllegalStateException().isThrownBy(() -> TestWebClientFactory.create(
|
||||
prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("wrong".toCharArray(), "1"))));
|
||||
assertThatIllegalStateException().isThrownBy(() -> TestWebClientFactory
|
||||
.create(prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("wrong".toCharArray(), "1"))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -66,7 +66,8 @@ class ClientCertificateAuthenticationStepsIntegrationTests extends ClientCertifi
|
||||
|
||||
assertThatExceptionOfType(NestedRuntimeException.class).isThrownBy(
|
||||
() -> new AuthenticationStepsExecutor(ClientCertificateAuthentication.createAuthenticationSteps(),
|
||||
restTemplate).login());
|
||||
restTemplate)
|
||||
.login());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -59,13 +59,15 @@ class ClientCertificateAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainToken() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/my/path/login")).andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/my/path/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
ClientCertificateAuthenticationOptions options = ClientCertificateAuthenticationOptions.builder()
|
||||
.path("my/path").build();
|
||||
.path("my/path")
|
||||
.build();
|
||||
|
||||
ClientCertificateAuthentication sut = new ClientCertificateAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -81,10 +83,10 @@ class ClientCertificateAuthenticationUnitTests {
|
||||
void loginShouldFail() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/cert/login")) //
|
||||
.andRespond(withServerError());
|
||||
.andRespond(withServerError());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new ClientCertificateAuthentication(this.restTemplate).login());
|
||||
.isThrownBy(() -> new ClientCertificateAuthentication(this.restTemplate).login());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -62,9 +62,11 @@ import static org.springframework.vault.util.Settings.findWorkDir;
|
||||
*/
|
||||
class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport {
|
||||
|
||||
static final Policy POLICY = Policy
|
||||
.of(Policy.Rule.builder().path("/*").capabilities(Policy.BuiltinCapabilities.READ,
|
||||
Policy.BuiltinCapabilities.CREATE, Policy.BuiltinCapabilities.UPDATE).build());
|
||||
static final Policy POLICY = Policy.of(Policy.Rule.builder()
|
||||
.path("/*")
|
||||
.capabilities(Policy.BuiltinCapabilities.READ, Policy.BuiltinCapabilities.CREATE,
|
||||
Policy.BuiltinCapabilities.UPDATE)
|
||||
.build());
|
||||
|
||||
@BeforeEach
|
||||
void before() {
|
||||
@@ -80,10 +82,11 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport
|
||||
}
|
||||
|
||||
RestTemplateBuilder devRestTemplate = RestTemplateBuilder.builder()
|
||||
.requestFactory(
|
||||
ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
|
||||
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).customizers(restTemplate -> restTemplate
|
||||
.getInterceptors().add(VaultClients.createNamespaceInterceptor("dev")));
|
||||
.requestFactory(
|
||||
ClientHttpRequestFactoryFactory.create(new ClientOptions(), Settings.createSslConfiguration()))
|
||||
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
|
||||
.customizers(
|
||||
restTemplate -> restTemplate.getInterceptors().add(VaultClients.createNamespaceInterceptor("dev")));
|
||||
|
||||
VaultTemplate dev = new VaultTemplate(devRestTemplate,
|
||||
new SimpleSessionManager(new TokenAuthentication(Settings.token())));
|
||||
@@ -130,8 +133,9 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport
|
||||
ClientCertificateAuthenticationIntegrationTestBase.prepareCertAuthenticationMethod());
|
||||
|
||||
RestTemplateBuilder builder = RestTemplateBuilder.builder()
|
||||
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT).requestFactory(clientHttpRequestFactory)
|
||||
.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev");
|
||||
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
|
||||
.requestFactory(clientHttpRequestFactory)
|
||||
.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev");
|
||||
|
||||
RestTemplate forAuthentication = builder.build();
|
||||
|
||||
@@ -150,8 +154,10 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport
|
||||
ClientHttpConnector connector = ClientHttpConnectorFactory.create(new ClientOptions(),
|
||||
ClientCertificateAuthenticationIntegrationTestBase.prepareCertAuthenticationMethod());
|
||||
|
||||
WebClientBuilder builder = WebClientBuilder.builder().endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
|
||||
.httpConnector(connector).defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev");
|
||||
WebClientBuilder builder = WebClientBuilder.builder()
|
||||
.endpoint(TestRestTemplateFactory.TEST_VAULT_ENDPOINT)
|
||||
.httpConnector(connector)
|
||||
.defaultHeader(VaultHttpHeaders.VAULT_NAMESPACE, "dev");
|
||||
|
||||
WebClient forAuthentication = builder.build();
|
||||
|
||||
@@ -161,8 +167,9 @@ class ClientCertificateNamespaceIntegrationTests extends IntegrationTestSupport
|
||||
|
||||
ReactiveVaultTemplate dev = new ReactiveVaultTemplate(builder, operator);
|
||||
|
||||
dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev")).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
dev.write("dev-secrets/my-secret", Collections.singletonMap("key", "dev"))
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
dev.read("dev-secrets/my-secret").as(StepVerifier::create).consumeNextWith(actual -> {
|
||||
|
||||
|
||||
@@ -43,8 +43,10 @@ class CubbyholeAuthenticationIntegrationTests extends CubbyholeAuthenticationInt
|
||||
String initialToken = wrapInfo.get("token");
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of(initialToken)).wrapped()
|
||||
.build();
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.initialToken(VaultToken.of(initialToken))
|
||||
.wrapped()
|
||||
.build();
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, restTemplate);
|
||||
@@ -56,7 +58,10 @@ class CubbyholeAuthenticationIntegrationTests extends CubbyholeAuthenticationInt
|
||||
void loginShouldFail() {
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of("Hello")).wrapped().build();
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.initialToken(VaultToken.of("Hello"))
|
||||
.wrapped()
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, restTemplate);
|
||||
|
||||
@@ -45,20 +45,22 @@ class CubbyholeAuthenticationOperatorIntegrationTests extends CubbyholeAuthentic
|
||||
String initialToken = wrapInfo.get("token");
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of(initialToken)).wrapped()
|
||||
.build();
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.initialToken(VaultToken.of(initialToken))
|
||||
.wrapped()
|
||||
.build();
|
||||
|
||||
AuthenticationStepsOperator operator = new AuthenticationStepsOperator(
|
||||
CubbyholeAuthentication.createAuthenticationSteps(options), this.webClient);
|
||||
|
||||
operator.getVaultToken() //
|
||||
.as(StepVerifier::create)
|
||||
//
|
||||
.consumeNextWith(actual -> {
|
||||
.as(StepVerifier::create)
|
||||
//
|
||||
.consumeNextWith(actual -> {
|
||||
|
||||
assertThat(actual).isNotEqualTo(Settings.token().getToken()).isNotNull();
|
||||
}) //
|
||||
.verifyComplete();
|
||||
assertThat(actual).isNotEqualTo(Settings.token().getToken()).isNotNull();
|
||||
}) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,8 +42,10 @@ class CubbyholeAuthenticationStepsIntegrationTests extends CubbyholeAuthenticati
|
||||
String initialToken = wrapInfo.get("token");
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints()).initialToken(VaultToken.of(initialToken)).wrapped()
|
||||
.build();
|
||||
.unwrappingEndpoints(getUnwrappingEndpoints())
|
||||
.initialToken(VaultToken.of(initialToken))
|
||||
.wrapped()
|
||||
.build();
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
|
||||
@@ -68,14 +68,17 @@ class CubbyholeAuthenticationUnitTests {
|
||||
+ "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":0,"
|
||||
+ "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }";
|
||||
|
||||
this.mockRest.expect(requestTo("/cubbyhole/response")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }"));
|
||||
this.mockRest.expect(requestTo("/cubbyhole/response"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\":{\"response\":" + this.OBJECT_MAPPER.writeValueAsString(wrappedResponse) + "} }"));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole).wrapped()
|
||||
.build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.unwrappingEndpoints(UnwrappingEndpoints.Cubbyhole)
|
||||
.wrapped()
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -96,13 +99,16 @@ class CubbyholeAuthenticationUnitTests {
|
||||
+ "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":0,"
|
||||
+ "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }";
|
||||
|
||||
this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));
|
||||
this.mockRest.expect(requestTo("/sys/wrapping/unwrap"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).unwrappingEndpoints(UnwrappingEndpoints.SysWrapping).wrapped()
|
||||
.build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.unwrappingEndpoints(UnwrappingEndpoints.SysWrapping)
|
||||
.wrapped()
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -123,17 +129,22 @@ class CubbyholeAuthenticationUnitTests {
|
||||
+ "\"auth\":{\"client_token\":\"5e6332cf-f003-6369-8cba-5bce2330f6cc\"," + "\"lease_duration\":10,"
|
||||
+ "\"accessor\":\"46b6aebb-187f-932a-26d7-4f3d86a68319\"} }";
|
||||
|
||||
this.mockRest.expect(requestTo("/sys/wrapping/unwrap")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));
|
||||
this.mockRest.expect(requestTo("/sys/wrapping/unwrap"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(wrappedResponse));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n"
|
||||
+ " \"creation_ttl\": 600,\n" + " \"renewable\": false,\n" + " \"ttl\": 456} }"));
|
||||
this.mockRest.expect(requestTo("/auth/token/lookup-self"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\": {\n" + " \"creation_ttl\": 600,\n" + " \"renewable\": false,\n"
|
||||
+ " \"ttl\": 456} }"));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).wrapped().build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.wrapped()
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -150,13 +161,17 @@ class CubbyholeAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldLoginUsingStoredLogin() {
|
||||
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }"));
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }"));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).path("cubbyhole/token").selfLookup(false).build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.path("cubbyhole/token")
|
||||
.selfLookup(false)
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -169,18 +184,23 @@ class CubbyholeAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldRetrieveRenewabilityUsingStoredLogin() {
|
||||
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }"));
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\":{\"mytoken\":\"058222ef-9ab9-ff39-f087-9d5bee64e46d\"} }"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "058222ef-9ab9-ff39-f087-9d5bee64e46d"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n"
|
||||
+ " \"creation_ttl\": 600,\n" + " \"renewable\": true,\n" + " \"ttl\": 456} }"));
|
||||
this.mockRest.expect(requestTo("/auth/token/lookup-self"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "058222ef-9ab9-ff39-f087-9d5bee64e46d"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\": {\n" + " \"creation_ttl\": 600,\n" + " \"renewable\": true,\n"
|
||||
+ " \"ttl\": 456} }"));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).path("cubbyhole/token").build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.path("cubbyhole/token")
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -197,12 +217,15 @@ class CubbyholeAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldFailUsingStoredLoginNoData() {
|
||||
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\":{} }"));
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\":{} }"));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).path("cubbyhole/token").build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.path("cubbyhole/token")
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -218,12 +241,16 @@ class CubbyholeAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldFailUsingStoredMultipleEntries() {
|
||||
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello")).andRespond(withSuccess()
|
||||
.contentType(MediaType.APPLICATION_JSON).body("{\"data\":{\"key1\":1, \"key2\":2} }"));
|
||||
this.mockRest.expect(requestTo("/cubbyhole/token"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "hello"))
|
||||
.andRespond(
|
||||
withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\":{\"key1\":1, \"key2\":2} }"));
|
||||
|
||||
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder()
|
||||
.initialToken(VaultToken.of("hello")).path("cubbyhole/token").build();
|
||||
.initialToken(VaultToken.of("hello"))
|
||||
.path("cubbyhole/token")
|
||||
.build();
|
||||
|
||||
CubbyholeAuthentication authentication = new CubbyholeAuthentication(options, this.restTemplate);
|
||||
|
||||
|
||||
@@ -56,14 +56,16 @@ class GcpComputeAuthenticationUnitTests {
|
||||
|
||||
this.mockRest.expect(requestTo(
|
||||
"http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://localhost:8200/vault/dev-role&format=full"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("my-jwt"));
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withSuccess().contentType(MediaType.TEXT_PLAIN).body("my-jwt"));
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/gcp/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role"))
|
||||
.andExpect(jsonPath("$.jwt").value("my-jwt"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -35,8 +35,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
|
||||
GoogleCredential credential = createGoogleCredential();
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential).role("foo")
|
||||
.build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.credential(credential)
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("hello@world");
|
||||
}
|
||||
@@ -46,8 +48,11 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
|
||||
GoogleCredential credential = createGoogleCredential();
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential)
|
||||
.serviceAccountId("override@foo.com").role("foo").build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.credential(credential)
|
||||
.serviceAccountId("override@foo.com")
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("override@foo.com");
|
||||
}
|
||||
@@ -57,9 +62,11 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
|
||||
GoogleCredential credential = createGoogleCredential();
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential)
|
||||
.serviceAccountIdAccessor((GoogleCredential googleCredential) -> "override@foo.com").role("foo")
|
||||
.build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.credential(credential)
|
||||
.serviceAccountIdAccessor((GoogleCredential googleCredential) -> "override@foo.com")
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("override@foo.com");
|
||||
}
|
||||
@@ -69,8 +76,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
|
||||
GoogleCredential credential = createGoogleCredential();
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential).role("foo")
|
||||
.build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.credential(credential)
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getProjectIdAccessor().getProjectId(credential)).isEqualTo("project-id");
|
||||
}
|
||||
@@ -80,8 +89,11 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
|
||||
GoogleCredential credential = createGoogleCredential();
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential)
|
||||
.projectId("my-project").role("foo").build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.credential(credential)
|
||||
.projectId("my-project")
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getProjectIdAccessor().getProjectId(credential)).isEqualTo("my-project");
|
||||
}
|
||||
@@ -91,8 +103,11 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
|
||||
GoogleCredential credential = createGoogleCredential();
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential)
|
||||
.projectIdAccessor((GoogleCredential googleCredential) -> "my-project").role("foo").build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.credential(credential)
|
||||
.projectIdAccessor((GoogleCredential googleCredential) -> "my-project")
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getProjectIdAccessor().getProjectId(credential)).isEqualTo("my-project");
|
||||
}
|
||||
@@ -100,8 +115,10 @@ class GcpIamAuthenticationOptionsBuilderUnitTests {
|
||||
private static GoogleCredential createGoogleCredential() {
|
||||
|
||||
GoogleCredential credential = new GoogleCredential.Builder().setServiceAccountId("hello@world")
|
||||
.setServiceAccountProjectId("project-id").setServiceAccountPrivateKey(mock(PrivateKey.class))
|
||||
.setServiceAccountPrivateKeyId("key-id").build();
|
||||
.setServiceAccountProjectId("project-id")
|
||||
.setServiceAccountPrivateKey(mock(PrivateKey.class))
|
||||
.setServiceAccountPrivateKeyId("key-id")
|
||||
.build();
|
||||
|
||||
credential.setAccessToken("foobar");
|
||||
|
||||
|
||||
@@ -68,25 +68,31 @@ class GcpIamAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldLogin() throws NoSuchAlgorithmException {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/gcp/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role"))
|
||||
.andExpect(jsonPath("$.jwt").value("my-jwt"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
|
||||
keyGen.initialize(1024);
|
||||
KeyPair key = keyGen.generateKeyPair();
|
||||
|
||||
GoogleCredential credential = new MockGoogleCredential.Builder().setServiceAccountId("hello@world")
|
||||
.setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(key.getPrivate())
|
||||
.setServiceAccountPrivateKeyId("key-id").setJsonFactory(new GsonFactory())
|
||||
.setTransport(new MockHttpTransport.Builder().setLowLevelHttpResponse(createMockHttpResponse()).build())
|
||||
.build();
|
||||
.setServiceAccountProjectId("foobar")
|
||||
.setServiceAccountPrivateKey(key.getPrivate())
|
||||
.setServiceAccountPrivateKeyId("key-id")
|
||||
.setJsonFactory(new GsonFactory())
|
||||
.setTransport(new MockHttpTransport.Builder().setLowLevelHttpResponse(createMockHttpResponse()).build())
|
||||
.build();
|
||||
credential.setAccessToken("foobar");
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role")
|
||||
.credential(credential).build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.role("dev-role")
|
||||
.credential(credential)
|
||||
.build();
|
||||
GcpIamAuthentication authentication = new GcpIamAuthentication(options, this.restTemplate,
|
||||
new MockHttpTransport.Builder().setLowLevelHttpResponse(createMockHttpResponse()).build());
|
||||
|
||||
@@ -112,12 +118,16 @@ class GcpIamAuthenticationUnitTests {
|
||||
|
||||
PrivateKey privateKeyMock = mock(PrivateKey.class);
|
||||
GoogleCredential credential = new Builder().setServiceAccountId("hello@world")
|
||||
.setServiceAccountProjectId("foobar").setServiceAccountPrivateKey(privateKeyMock)
|
||||
.setServiceAccountPrivateKeyId("key-id").build();
|
||||
.setServiceAccountProjectId("foobar")
|
||||
.setServiceAccountPrivateKey(privateKeyMock)
|
||||
.setServiceAccountPrivateKeyId("key-id")
|
||||
.build();
|
||||
credential.setAccessToken("foobar");
|
||||
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().role("dev-role")
|
||||
.credential(credential).build();
|
||||
GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder()
|
||||
.role("dev-role")
|
||||
.credential(credential)
|
||||
.build();
|
||||
|
||||
new GcpIamAuthentication(options, this.restTemplate);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,9 @@ class GcpIamCredentialsAuthenticationOptionsBuilderUnitTests {
|
||||
ServiceAccountCredentials credentials = createServiceAccountCredentials();
|
||||
|
||||
GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder()
|
||||
.credentials(credentials).role("foo").build();
|
||||
.credentials(credentials)
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credentials)).isEqualTo("hello@world");
|
||||
}
|
||||
@@ -51,7 +53,10 @@ class GcpIamCredentialsAuthenticationOptionsBuilderUnitTests {
|
||||
ServiceAccountCredentials credential = createServiceAccountCredentials();
|
||||
|
||||
GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder()
|
||||
.credentials(credential).serviceAccountId("override@foo.com").role("foo").build();
|
||||
.credentials(credential)
|
||||
.serviceAccountId("override@foo.com")
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("override@foo.com");
|
||||
}
|
||||
@@ -62,17 +67,22 @@ class GcpIamCredentialsAuthenticationOptionsBuilderUnitTests {
|
||||
ServiceAccountCredentials credential = createServiceAccountCredentials();
|
||||
|
||||
GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder()
|
||||
.credentials(credential)
|
||||
.serviceAccountIdAccessor((GoogleCredentials googleCredential) -> "override@foo.com").role("foo")
|
||||
.build();
|
||||
.credentials(credential)
|
||||
.serviceAccountIdAccessor((GoogleCredentials googleCredential) -> "override@foo.com")
|
||||
.role("foo")
|
||||
.build();
|
||||
|
||||
assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("override@foo.com");
|
||||
}
|
||||
|
||||
private static ServiceAccountCredentials createServiceAccountCredentials() {
|
||||
return (ServiceAccountCredentials) ServiceAccountCredentials.newBuilder().setClientEmail("hello@world")
|
||||
.setProjectId("project-id").setPrivateKey(mock(PrivateKey.class)).setPrivateKeyId("key-id")
|
||||
.setAccessToken(new AccessToken("foobar", new Date())).build();
|
||||
return (ServiceAccountCredentials) ServiceAccountCredentials.newBuilder()
|
||||
.setClientEmail("hello@world")
|
||||
.setProjectId("project-id")
|
||||
.setPrivateKey(mock(PrivateKey.class))
|
||||
.setPrivateKeyId("key-id")
|
||||
.setAccessToken(new AccessToken("foobar", new Date()))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -83,19 +83,20 @@ class GcpIamCredentialsAuthenticationUnitTests {
|
||||
this.restTemplate = restTemplate;
|
||||
|
||||
String serverName = InProcessServerBuilder.generateName();
|
||||
this.server = InProcessServerBuilder.forName(serverName).directExecutor()
|
||||
.addService(ServerServiceDefinition.builder("google.iam.credentials.v1.IAMCredentials")
|
||||
.addMethod(
|
||||
MethodDescriptor
|
||||
.newBuilder(ProtoLiteUtils.marshaller(SignJwtRequest.getDefaultInstance()),
|
||||
ProtoLiteUtils.marshaller(SignJwtResponse.getDefaultInstance()))
|
||||
.setType(MethodDescriptor.MethodType.UNARY)
|
||||
.setFullMethodName("google.iam.credentials.v1.IAMCredentials/SignJwt").build(),
|
||||
asyncUnaryCall((request, responseObserver) -> {
|
||||
this.serverCall.invoke(request, responseObserver);
|
||||
}))
|
||||
.build())
|
||||
.build().start();
|
||||
this.server = InProcessServerBuilder.forName(serverName)
|
||||
.directExecutor()
|
||||
.addService(ServerServiceDefinition.builder("google.iam.credentials.v1.IAMCredentials")
|
||||
.addMethod(MethodDescriptor
|
||||
.newBuilder(ProtoLiteUtils.marshaller(SignJwtRequest.getDefaultInstance()),
|
||||
ProtoLiteUtils.marshaller(SignJwtResponse.getDefaultInstance()))
|
||||
.setType(MethodDescriptor.MethodType.UNARY)
|
||||
.setFullMethodName("google.iam.credentials.v1.IAMCredentials/SignJwt")
|
||||
.build(), asyncUnaryCall((request, responseObserver) -> {
|
||||
this.serverCall.invoke(request, responseObserver);
|
||||
}))
|
||||
.build())
|
||||
.build()
|
||||
.start();
|
||||
this.managedChannel = InProcessChannelBuilder.forName(serverName).directExecutor().build();
|
||||
}
|
||||
|
||||
@@ -107,26 +108,35 @@ class GcpIamCredentialsAuthenticationUnitTests {
|
||||
@Test
|
||||
void shouldLogin() {
|
||||
this.serverCall = ((request, responseObserver) -> {
|
||||
SignJwtResponse signJwtResponse = SignJwtResponse.newBuilder().setSignedJwt("my-jwt").setKeyId("key-id")
|
||||
.build();
|
||||
SignJwtResponse signJwtResponse = SignJwtResponse.newBuilder()
|
||||
.setSignedJwt("my-jwt")
|
||||
.setKeyId("key-id")
|
||||
.build();
|
||||
responseObserver.onNext(signJwtResponse);
|
||||
responseObserver.onCompleted();
|
||||
});
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
|
||||
"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
this.mockRest.expect(requestTo("/auth/gcp/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role"))
|
||||
.andExpect(jsonPath("$.jwt").value("my-jwt"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
|
||||
+ "}"));
|
||||
|
||||
PrivateKey privateKeyMock = mock(PrivateKey.class);
|
||||
ServiceAccountCredentials credential = (ServiceAccountCredentials) ServiceAccountCredentials.newBuilder()
|
||||
.setClientEmail("hello@world").setProjectId("foobar").setPrivateKey(privateKeyMock)
|
||||
.setPrivateKeyId("key-id")
|
||||
.setAccessToken(new AccessToken("foobar", Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))).build();
|
||||
.setClientEmail("hello@world")
|
||||
.setProjectId("foobar")
|
||||
.setPrivateKey(privateKeyMock)
|
||||
.setPrivateKeyId("key-id")
|
||||
.setAccessToken(new AccessToken("foobar", Date.from(Instant.now().plus(1, ChronoUnit.DAYS))))
|
||||
.build();
|
||||
|
||||
GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder()
|
||||
.role("dev-role").credentials(credential).build();
|
||||
.role("dev-role")
|
||||
.credentials(credential)
|
||||
.build();
|
||||
GcpIamCredentialsAuthentication authentication = new GcpIamCredentialsAuthentication(options, this.restTemplate,
|
||||
FixedTransportChannelProvider.create(GrpcTransportChannel.create(managedChannel)));
|
||||
|
||||
@@ -145,12 +155,17 @@ class GcpIamCredentialsAuthenticationUnitTests {
|
||||
|
||||
PrivateKey privateKeyMock = mock(PrivateKey.class);
|
||||
ServiceAccountCredentials credential = (ServiceAccountCredentials) ServiceAccountCredentials.newBuilder()
|
||||
.setClientEmail("hello@world").setProjectId("foobar").setPrivateKey(privateKeyMock)
|
||||
.setPrivateKeyId("key-id")
|
||||
.setAccessToken(new AccessToken("foobar", Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))).build();
|
||||
.setClientEmail("hello@world")
|
||||
.setProjectId("foobar")
|
||||
.setPrivateKey(privateKeyMock)
|
||||
.setPrivateKeyId("key-id")
|
||||
.setAccessToken(new AccessToken("foobar", Date.from(Instant.now().plus(1, ChronoUnit.DAYS))))
|
||||
.build();
|
||||
|
||||
GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder()
|
||||
.role("dev-role").credentials(credential).build();
|
||||
.role("dev-role")
|
||||
.credentials(credential)
|
||||
.build();
|
||||
|
||||
new GcpIamCredentialsAuthentication(options, this.restTemplate);
|
||||
}
|
||||
|
||||
@@ -42,8 +42,10 @@ class KubernetesAuthenticationIntegrationTests extends KubernetesAuthenticationI
|
||||
|
||||
File tokenFile = new File(findWorkDir(), "minikube/hello-minikube-token");
|
||||
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("my-role")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile)).build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("my-role")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile))
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
@@ -58,13 +60,15 @@ class KubernetesAuthenticationIntegrationTests extends KubernetesAuthenticationI
|
||||
|
||||
File tokenFile = new File(findWorkDir(), "minikube/hello-minikube-token");
|
||||
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("wrong")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile)).build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("wrong")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile))
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new KubernetesAuthentication(options, restTemplate).login());
|
||||
.isThrownBy(() -> new KubernetesAuthentication(options, restTemplate).login());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,13 +76,15 @@ class KubernetesAuthenticationIntegrationTests extends KubernetesAuthenticationI
|
||||
|
||||
ClassPathResource tokenResource = new ClassPathResource("kube-jwt-token");
|
||||
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("my-role")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenResource)).build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("my-role")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenResource))
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new KubernetesAuthentication(options, restTemplate).login());
|
||||
.isThrownBy(() -> new KubernetesAuthentication(options, restTemplate).login());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,8 +40,10 @@ class KubernetesAuthenticationStepsIntegrationTests extends KubernetesAuthentica
|
||||
|
||||
File tokenFile = new File(findWorkDir(), "minikube/hello-minikube-token");
|
||||
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("my-role")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile)).build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("my-role")
|
||||
.jwtSupplier(new KubernetesServiceAccountTokenFile(tokenFile))
|
||||
.build();
|
||||
|
||||
RestTemplate restTemplate = TestRestTemplateFactory.create(Settings.createSslConfiguration());
|
||||
|
||||
|
||||
@@ -60,13 +60,17 @@ class KubernetesAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainTokenWithStaticJwtSupplier() {
|
||||
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello") //
|
||||
.jwtSupplier(() -> "my-jwt-token").build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("hello") //
|
||||
.jwtSupplier(() -> "my-jwt-token")
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/kubernetes/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("hello")).andExpect(jsonPath("$.jwt").value("my-jwt-token"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/kubernetes/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("hello"))
|
||||
.andExpect(jsonPath("$.jwt").value("my-jwt-token"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
|
||||
KubernetesAuthentication authentication = new KubernetesAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -78,29 +82,35 @@ class KubernetesAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldFail() {
|
||||
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello")
|
||||
.jwtSupplier(() -> "my-jwt-token").build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("hello")
|
||||
.jwtSupplier(() -> "my-jwt-token")
|
||||
.build();
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/kubernetes/login")) //
|
||||
.andRespond(withServerError());
|
||||
.andRespond(withServerError());
|
||||
|
||||
assertThatExceptionOfType(VaultException.class)
|
||||
.isThrownBy(() -> new KubernetesAuthentication(options, this.restTemplate).login());
|
||||
.isThrownBy(() -> new KubernetesAuthentication(options, this.restTemplate).login());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReuseCachedToken() {
|
||||
|
||||
AtomicReference<String> token = new AtomicReference<>("foo");
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder().role("hello") //
|
||||
.jwtSupplier(((KubernetesJwtSupplier) token::get).cached()).build();
|
||||
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
|
||||
.role("hello") //
|
||||
.jwtSupplier(((KubernetesJwtSupplier) token::get).cached())
|
||||
.build();
|
||||
|
||||
token.set("bar");
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/kubernetes/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("hello")).andExpect(jsonPath("$.jwt").value("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/kubernetes/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("hello"))
|
||||
.andExpect(jsonPath("$.jwt").value("foo"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
|
||||
KubernetesAuthentication authentication = new KubernetesAuthentication(options, this.restTemplate);
|
||||
|
||||
|
||||
@@ -73,9 +73,10 @@ class LifecycleAwareSessionManagerIntegrationTests extends IntegrationTestSuppor
|
||||
VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken();
|
||||
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder() //
|
||||
.renewable().ttl(1, TimeUnit.HOURS) //
|
||||
.explicitMaxTtl(10, TimeUnit.HOURS) //
|
||||
.build();
|
||||
.renewable()
|
||||
.ttl(1, TimeUnit.HOURS) //
|
||||
.explicitMaxTtl(10, TimeUnit.HOURS) //
|
||||
.build();
|
||||
|
||||
VaultToken token = tokenOperations.create(tokenRequest).getToken();
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ class LifecycleAwareSessionManagerUnitTests {
|
||||
when(this.clientAuthentication.login()).thenReturn(VaultToken.of("login"));
|
||||
|
||||
when(this.restOperations.exchange(anyString(), any(), any(), ArgumentMatchers.<Class>any()))
|
||||
.thenReturn(new ResponseEntity<>(vaultResponse, HttpStatus.OK));
|
||||
.thenReturn(new ResponseEntity<>(vaultResponse, HttpStatus.OK));
|
||||
|
||||
LoginToken sessionToken = (LoginToken) this.sessionManager.getSessionToken();
|
||||
assertThat(sessionToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(100));
|
||||
@@ -140,7 +140,7 @@ class LifecycleAwareSessionManagerUnitTests {
|
||||
when(this.clientAuthentication.login()).thenReturn(VaultToken.of("login"));
|
||||
|
||||
when(this.restOperations.exchange(anyString(), any(), any(), ArgumentMatchers.<Class>any()))
|
||||
.thenThrow(new HttpClientErrorException(HttpStatus.FORBIDDEN));
|
||||
.thenThrow(new HttpClientErrorException(HttpStatus.FORBIDDEN));
|
||||
|
||||
VaultToken sessionToken = this.sessionManager.getSessionToken();
|
||||
assertThat(sessionToken).isExactlyInstanceOf(VaultToken.class);
|
||||
@@ -375,7 +375,7 @@ class LifecycleAwareSessionManagerUnitTests {
|
||||
this.restOperations);
|
||||
|
||||
when(this.clientAuthentication.login())
|
||||
.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
|
||||
.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
|
||||
|
||||
ArgumentCaptor<Trigger> triggerCaptor = ArgumentCaptor.forClass(Trigger.class);
|
||||
|
||||
|
||||
@@ -56,10 +56,12 @@ class LoginTokenAdapterUnitTests {
|
||||
@Test
|
||||
void shouldSelfLookupToken() throws Exception {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/token/lookup-self")).andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{\"data\": {\n"
|
||||
+ " \"creation_ttl\": 600,\n" + " \"renewable\": false,\n" + " \"ttl\": 456} }"));
|
||||
this.mockRest.expect(requestTo("/auth/token/lookup-self"))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andExpect(header(VaultHttpHeaders.VAULT_TOKEN, "5e6332cf-f003-6369-8cba-5bce2330f6cc"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"data\": {\n" + " \"creation_ttl\": 600,\n" + " \"renewable\": false,\n"
|
||||
+ " \"ttl\": 456} }"));
|
||||
|
||||
LoginTokenAdapter adapter = new LoginTokenAdapter(
|
||||
new TokenAuthentication("5e6332cf-f003-6369-8cba-5bce2330f6cc"), this.restTemplate);
|
||||
|
||||
@@ -41,11 +41,11 @@ class LoginTokenUnitTests {
|
||||
|
||||
assertThat(LoginToken.of("token")).hasToString("LoginToken [renewable=false, leaseDuration=PT0S, type=null]");
|
||||
assertThat(LoginToken.of("token".toCharArray(), Duration.ofSeconds(1)))
|
||||
.hasToString("LoginToken [renewable=false, leaseDuration=PT1S, type=null]");
|
||||
.hasToString("LoginToken [renewable=false, leaseDuration=PT1S, type=null]");
|
||||
assertThat(LoginToken.renewable("token".toCharArray(), Duration.ofSeconds(1)))
|
||||
.hasToString("LoginToken [renewable=true, leaseDuration=PT1S, type=null]");
|
||||
.hasToString("LoginToken [renewable=true, leaseDuration=PT1S, type=null]");
|
||||
assertThat(LoginToken.builder().token("foo").type("service").build())
|
||||
.hasToString("LoginToken [renewable=false, leaseDuration=PT0S, type=service]");
|
||||
.hasToString("LoginToken [renewable=false, leaseDuration=PT0S, type=service]");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -30,8 +30,8 @@ class PcfAuthenticationOptionsUnitTests {
|
||||
void emptyEnvVariableShouldFailWithMeaningfulMessage() {
|
||||
|
||||
assertThatThrownBy(() -> PcfAuthenticationOptions.builder().role("my-role").build())
|
||||
.isInstanceOf(IllegalStateException.class) //
|
||||
.hasMessageContaining("Environment variable CF_INSTANCE_CERT not set");
|
||||
.isInstanceOf(IllegalStateException.class) //
|
||||
.hasMessageContaining("Environment variable CF_INSTANCE_CERT not set");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -89,11 +89,12 @@ class PcfAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginShouldObtainToken() {
|
||||
|
||||
PcfAuthenticationOptions options = PcfAuthenticationOptions.builder().instanceCertificate(() -> "foo") //
|
||||
.instanceKey(() -> this.instanceKey) //
|
||||
.role("dev-role") //
|
||||
.clock(this.clock) //
|
||||
.build();
|
||||
PcfAuthenticationOptions options = PcfAuthenticationOptions.builder()
|
||||
.instanceCertificate(() -> "foo") //
|
||||
.instanceKey(() -> this.instanceKey) //
|
||||
.role("dev-role") //
|
||||
.clock(this.clock) //
|
||||
.build();
|
||||
|
||||
PcfAuthentication authentication = new PcfAuthentication(options, this.restTemplate);
|
||||
|
||||
@@ -107,11 +108,12 @@ class PcfAuthenticationUnitTests {
|
||||
@Test
|
||||
void loginWithStepsShouldObtainToken() {
|
||||
|
||||
PcfAuthenticationOptions options = PcfAuthenticationOptions.builder().instanceCertificate(() -> "foo") //
|
||||
.instanceKey(() -> this.instanceKey) //
|
||||
.role("dev-role") //
|
||||
.clock(this.clock) //
|
||||
.build();
|
||||
PcfAuthenticationOptions options = PcfAuthenticationOptions.builder()
|
||||
.instanceCertificate(() -> "foo") //
|
||||
.instanceKey(() -> this.instanceKey) //
|
||||
.role("dev-role") //
|
||||
.clock(this.clock) //
|
||||
.build();
|
||||
|
||||
expectLoginRequest();
|
||||
|
||||
@@ -125,12 +127,14 @@ class PcfAuthenticationUnitTests {
|
||||
|
||||
private void expectLoginRequest() {
|
||||
|
||||
this.mockRest.expect(requestTo("/auth/pcf/login")).andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.signature").exists())
|
||||
.andExpect(jsonPath("$.cf_instance_cert").value("foo"))
|
||||
.andExpect(jsonPath("$.signing_time").value("2007-12-03T10:15:30Z"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
this.mockRest.expect(requestTo("/auth/pcf/login"))
|
||||
.andExpect(method(HttpMethod.POST))
|
||||
.andExpect(jsonPath("$.role").value("dev-role"))
|
||||
.andExpect(jsonPath("$.signature").exists())
|
||||
.andExpect(jsonPath("$.cf_instance_cert").value("foo"))
|
||||
.andExpect(jsonPath("$.signing_time").value("2007-12-03T10:15:30Z"))
|
||||
.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{" + "\"auth\":{\"client_token\":\"my-token\"}" + "}"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -96,9 +96,9 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests extends IntegrationTe
|
||||
() -> Mono.just(loginToken), this.taskScheduler, prepare().getWebClient());
|
||||
|
||||
sessionManager.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
// Expect no exception to be thrown.
|
||||
@@ -108,9 +108,10 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests extends IntegrationTe
|
||||
VaultTokenOperations tokenOperations = prepare().getVaultOperations().opsForToken();
|
||||
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder() //
|
||||
.renewable().ttl(1, TimeUnit.HOURS) //
|
||||
.explicitMaxTtl(10, TimeUnit.HOURS) //
|
||||
.build();
|
||||
.renewable()
|
||||
.ttl(1, TimeUnit.HOURS) //
|
||||
.explicitMaxTtl(10, TimeUnit.HOURS) //
|
||||
.build();
|
||||
|
||||
VaultToken token = tokenOperations.create(tokenRequest).getToken();
|
||||
|
||||
@@ -133,13 +134,13 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests extends IntegrationTe
|
||||
};
|
||||
|
||||
sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
sessionManager.renewToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -152,9 +153,9 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests extends IntegrationTe
|
||||
prepare().getWebClient());
|
||||
|
||||
sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
sessionManager.destroy();
|
||||
|
||||
prepare().getVaultOperations().doWithSession(restOperations -> {
|
||||
@@ -182,9 +183,9 @@ class ReactiveLifecycleAwareSessionManagerIntegrationTests extends IntegrationTe
|
||||
prepare().getWebClient());
|
||||
|
||||
sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(loginToken) //
|
||||
.verifyComplete();
|
||||
sessionManager.revokeNow();
|
||||
|
||||
prepare().getVaultOperations().doWithSession(restOperations -> {
|
||||
|
||||
@@ -138,9 +138,9 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
mockToken(LoginToken.of("login"));
|
||||
|
||||
this.sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(LoginToken.of("login")) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNext(LoginToken.of("login")) //
|
||||
.verifyComplete();
|
||||
verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
|
||||
}
|
||||
|
||||
@@ -188,14 +188,15 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
|
||||
mockToken(VaultToken.of("login"));
|
||||
|
||||
when(this.responseSpec.bodyToMono((Class) any())).thenReturn(
|
||||
Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null)));
|
||||
when(this.responseSpec.bodyToMono((Class) any()))
|
||||
.thenReturn(Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null)));
|
||||
|
||||
this.sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.assertNext(it -> {
|
||||
assertThat(it).isExactlyInstanceOf(VaultToken.class);
|
||||
}).verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.assertNext(it -> {
|
||||
assertThat(it).isExactlyInstanceOf(VaultToken.class);
|
||||
})
|
||||
.verifyComplete();
|
||||
verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
|
||||
verify(this.errorListener).onAuthenticationError(any());
|
||||
}
|
||||
@@ -205,8 +206,8 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
|
||||
mockToken(LoginToken.renewable("foo".toCharArray(), Duration.ofMinutes(1)));
|
||||
|
||||
when(this.responseSpec.bodyToMono((Class) any())).thenReturn(Mono.error(
|
||||
new WebClientResponseException("Some server error", 500, "Some server error", null, null, null)));
|
||||
when(this.responseSpec.bodyToMono((Class) any())).thenReturn(Mono
|
||||
.error(new WebClientResponseException("Some server error", 500, "Some server error", null, null, null)));
|
||||
|
||||
AtomicReference<AuthenticationErrorEvent> listener = new AtomicReference<>();
|
||||
this.sessionManager.addErrorListener(listener::set);
|
||||
@@ -214,8 +215,8 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
this.sessionManager.getVaultToken().as(StepVerifier::create).expectNextCount(1).verifyComplete();
|
||||
this.sessionManager.renewToken().as(StepVerifier::create).verifyComplete();
|
||||
assertThat(listener.get().getException()).isInstanceOf(VaultTokenRenewalException.class)
|
||||
.hasCauseInstanceOf(WebClientResponseException.class)
|
||||
.hasMessageContaining("Cannot renew token: Status 500 Some server error");
|
||||
.hasCauseInstanceOf(WebClientResponseException.class)
|
||||
.hasMessageContaining("Cannot renew token: Status 500 Some server error");
|
||||
|
||||
}
|
||||
|
||||
@@ -229,9 +230,9 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
when(this.responseSpec.bodyToMono(String.class)).thenReturn(Mono.just("OK"));
|
||||
|
||||
this.sessionManager.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
|
||||
this.sessionManager.destroy();
|
||||
|
||||
@@ -247,9 +248,9 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
|
||||
this.sessionManager.setTokenSelfLookupEnabled(false);
|
||||
this.sessionManager.renewToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
this.sessionManager.destroy();
|
||||
|
||||
verify(this.webClient, never()).post();
|
||||
@@ -267,9 +268,9 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
|
||||
this.sessionManager.setTokenSelfLookupEnabled(false);
|
||||
this.sessionManager.renewToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
this.sessionManager.destroy();
|
||||
|
||||
verify(this.webClient, never()).post();
|
||||
@@ -283,13 +284,13 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
|
||||
mockToken(LoginToken.of("login"));
|
||||
|
||||
when(this.responseSpec.bodyToMono((Class) any())).thenReturn(
|
||||
Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null)));
|
||||
when(this.responseSpec.bodyToMono((Class) any()))
|
||||
.thenReturn(Mono.error(new WebClientResponseException("forbidden", 403, "Forbidden", null, null, null)));
|
||||
|
||||
this.sessionManager.renewToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
this.sessionManager.destroy();
|
||||
|
||||
verify(this.requestBodyUriSpec).uri("auth/token/revoke-self");
|
||||
@@ -301,9 +302,9 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
|
||||
|
||||
this.sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
|
||||
verify(this.taskScheduler).schedule(any(Runnable.class), any(Trigger.class));
|
||||
}
|
||||
@@ -323,9 +324,9 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
when(this.responseSpec.bodyToMono(VaultResponse.class)).thenReturn(Mono.just(vaultResponse));
|
||||
|
||||
this.sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
|
||||
verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
|
||||
|
||||
@@ -345,14 +346,14 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
|
||||
|
||||
when(this.responseSpec.bodyToMono(VaultResponse.class))
|
||||
.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))));
|
||||
.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(10)))));
|
||||
|
||||
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
|
||||
this.sessionManager.getSessionToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
|
||||
|
||||
runnableCaptor.getValue().run();
|
||||
@@ -365,7 +366,7 @@ class ReactiveLifecycleAwareSessionManagerUnitTests {
|
||||
|
||||
mockToken(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
|
||||
when(this.responseSpec.bodyToMono(VaultResponse.class))
|
||||
.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))));
|
||||
.thenReturn(Mono.just(fromToken(LoginToken.of("foo".toCharArray(), Duration.ofSeconds(2)))));
|
||||
|
||||
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
|
||||
|
||||
|
||||
@@ -42,8 +42,11 @@ class TokenAuthenticationOperatorIntegrationTests extends TokenAuthenticationInt
|
||||
@Test
|
||||
void shouldSelfLookup() {
|
||||
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1)
|
||||
.build();
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder()
|
||||
.ttl(Duration.ofSeconds(60))
|
||||
.renewable()
|
||||
.numUses(1)
|
||||
.build();
|
||||
|
||||
VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken();
|
||||
|
||||
@@ -65,8 +68,11 @@ class TokenAuthenticationOperatorIntegrationTests extends TokenAuthenticationInt
|
||||
@Test
|
||||
void shouldFailDuringSelfLookup() {
|
||||
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1)
|
||||
.build();
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder()
|
||||
.ttl(Duration.ofSeconds(60))
|
||||
.renewable()
|
||||
.numUses(1)
|
||||
.build();
|
||||
|
||||
VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken();
|
||||
|
||||
@@ -75,14 +81,14 @@ class TokenAuthenticationOperatorIntegrationTests extends TokenAuthenticationInt
|
||||
|
||||
// first usage
|
||||
operator.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
.as(StepVerifier::create) //
|
||||
.expectNextCount(1) //
|
||||
.verifyComplete();
|
||||
|
||||
operator.getVaultToken() //
|
||||
.as(StepVerifier::create) //
|
||||
.expectError(VaultException.class) //
|
||||
.verify();
|
||||
.as(StepVerifier::create) //
|
||||
.expectError(VaultException.class) //
|
||||
.verify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,8 +42,11 @@ class TokenAuthenticationStepsIntegrationTests extends TokenAuthenticationIntegr
|
||||
@Test
|
||||
void shouldSelfLookup() {
|
||||
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1)
|
||||
.build();
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder()
|
||||
.ttl(Duration.ofSeconds(60))
|
||||
.renewable()
|
||||
.numUses(1)
|
||||
.build();
|
||||
|
||||
VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken();
|
||||
|
||||
@@ -62,8 +65,11 @@ class TokenAuthenticationStepsIntegrationTests extends TokenAuthenticationIntegr
|
||||
@Test
|
||||
void shouldFailDuringSelfLookup() {
|
||||
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder().ttl(Duration.ofSeconds(60)).renewable().numUses(1)
|
||||
.build();
|
||||
VaultTokenRequest tokenRequest = VaultTokenRequest.builder()
|
||||
.ttl(Duration.ofSeconds(60))
|
||||
.renewable()
|
||||
.numUses(1)
|
||||
.build();
|
||||
|
||||
VaultToken token = prepare().getVaultOperations().opsForToken().create(tokenRequest).getToken();
|
||||
|
||||
|
||||
@@ -48,9 +48,9 @@ public abstract class UsernamePasswordAuthenticationIntegrationTestBase extends
|
||||
|
||||
prepare().getVaultOperations().opsForSys().createOrUpdatePolicy(DEFAULT_USERPASS_AUTHENTICATION_PATH, POLICY);
|
||||
prepare().getVaultOperations()
|
||||
.doWithSession(restOperations -> restOperations.postForEntity(
|
||||
String.format("auth/%s/users/%s", DEFAULT_USERPASS_AUTHENTICATION_PATH, username),
|
||||
singletonMap("password", password), Map.class));
|
||||
.doWithSession(restOperations -> restOperations.postForEntity(
|
||||
String.format("auth/%s/users/%s", DEFAULT_USERPASS_AUTHENTICATION_PATH, username),
|
||||
singletonMap("password", password), Map.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -37,7 +37,9 @@ class UsernamePasswordAuthenticationIntegrationTests extends UsernamePasswordAut
|
||||
void shouldLoginSuccessfully() {
|
||||
|
||||
UsernamePasswordAuthenticationOptions options = UsernamePasswordAuthenticationOptions.builder()
|
||||
.username(username).password(password).build();
|
||||
.username(username)
|
||||
.password(password)
|
||||
.build();
|
||||
|
||||
UsernamePasswordAuthentication authentication = new UsernamePasswordAuthentication(options, restTemplate);
|
||||
VaultToken login = authentication.login();
|
||||
@@ -49,7 +51,9 @@ class UsernamePasswordAuthenticationIntegrationTests extends UsernamePasswordAut
|
||||
void shouldLoginUsingAuthenticationSteps() {
|
||||
|
||||
UsernamePasswordAuthenticationOptions options = UsernamePasswordAuthenticationOptions.builder()
|
||||
.username(username).password(password).build();
|
||||
.username(username)
|
||||
.password(password)
|
||||
.build();
|
||||
|
||||
AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(
|
||||
UsernamePasswordAuthentication.createAuthenticationSteps(options), restTemplate);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user