Skip to content

Commit

Permalink
Add password()
Browse files Browse the repository at this point in the history
  • Loading branch information
d-frey committed Dec 6, 2024
1 parent 8d2f5d8 commit f81d13b
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/tao/pq/connection.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ namespace tao::pq
void set_timeout( const std::chrono::milliseconds timeout );
void reset_timeout() noexcept;

[[nodiscard]] auto password( const internal::zsv passwd, const internal::zsv user, const internal::zsv algorithm = "scram-sha-256" ) -> std::string;

[[nodiscard]] auto underlying_raw_ptr() noexcept -> PGconn*
{
return m_pgconn.get();
Expand Down
9 changes: 9 additions & 0 deletions src/lib/pq/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -611,4 +611,13 @@ namespace tao::pq
m_timeout = std::nullopt;
}

auto connection::password( const internal::zsv passwd, const internal::zsv user, const internal::zsv algorithm ) -> std::string
{
std::unique_ptr< char, decltype( &PQfreemem ) > buffer( PQencryptPasswordConn( m_pgconn.get(), passwd, user, algorithm ), &PQfreemem );
if( !buffer ) {
throw std::invalid_argument( PQerrorMessage( m_pgconn.get() ) ); // LCOV_EXCL_LINE
}
return buffer.get();
}

} // namespace tao::pq
50 changes: 50 additions & 0 deletions src/test/pq/password.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) 2024 Daniel Frey and Dr. Colin Hirsch
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)

#include "../getenv.hpp"
#include "../macros.hpp"

#include <exception>
#include <format>
#include <iostream>

#include <tao/pq.hpp>

namespace
{
void run()
{
// overwrite the default with an environment variable if needed
const auto connection_string = tao::pq::internal::getenv( "TAOPQ_TEST_DATABASE", "dbname=template1" );

// open a connection to the database
const auto conn = tao::pq::connection::create( connection_string );

// prevent cleartext passwords from showing up in logs, traces, etc.
const auto cleartext_password = "secret123";
const auto encrypted_password = conn->password( cleartext_password, "tao_test_role" );

// execute commands
conn->execute( "DROP ROLE IF EXISTS tao_test_role" );
conn->execute( std::format( "CREATE ROLE tao_test_role PASSWORD '{}'", encrypted_password ) );
}

} // namespace

auto main() -> int // NOLINT(bugprone-exception-escape)
{
try {
run();
}
// LCOV_EXCL_START
catch( const std::exception& e ) {
std::cerr << "exception: " << e.what() << '\n';
throw;
}
catch( ... ) {
std::cerr << "unknown exception\n";
throw;
}
// LCOV_EXCL_STOP
}

0 comments on commit f81d13b

Please sign in to comment.