diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index dfdb8b7..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.sh text eol=lf diff --git a/Dockerfile b/Dockerfile index d18fbf9..399c36b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,7 +7,6 @@ COPY go.mod go.sum ./ RUN go mod download COPY src ./src -COPY cmd ./cmd RUN CGO_ENABLED=0 \ GOOS=linux \ @@ -17,14 +16,6 @@ RUN CGO_ENABLED=0 \ -o /out/messenger \ ./src -# healthcheck script build -RUN CGO_ENABLED=0 \ - GOOS=linux \ - go build \ - -trimpath \ - -ldflags="-s -w" \ - -o /out/healthcheck \ - ./cmd/healthcheck FROM debian:12.15-slim @@ -34,7 +25,6 @@ RUN groupadd --system app \ WORKDIR /app COPY --from=builder /out/messenger ./messenger -COPY --from=builder /out/healthcheck ./healthcheck ENV APP_HOST=0.0.0.0 ENV APP_PORT=8080 @@ -42,7 +32,7 @@ ENV APP_PORT=8080 EXPOSE 8080 HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ - CMD ["./healthcheck"] + CMD ["./messenger", "healthcheck"] USER app:app diff --git a/Makefile b/Makefile index 0c498d9..9ecb223 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate unit test load test-persistence +.PHONY: help check validate test load test-persistence help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -15,9 +15,6 @@ check: validate: $(PYTHON) scripts/validate_openapi.py -unit: - go test ./... - test: $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/cmd/healthcheck/main.go b/cmd/healthcheck/main.go deleted file mode 100644 index c5e6005..0000000 --- a/cmd/healthcheck/main.go +++ /dev/null @@ -1,24 +0,0 @@ -package main - -import ( - "net/http" - "os" - "time" -) - -func main() { - client := http.Client{ - Timeout: 2 * time.Second, - } - - response, err := client.Get("http://127.0.0.1:8080/health/ready") - if err != nil { - os.Exit(1) - } - - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - os.Exit(1) - } -} diff --git a/compose.yaml b/compose.yaml index a9811f0..32630e1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -25,7 +25,7 @@ services: db: condition: service_healthy healthcheck: - test: ["CMD", "./healthcheck"] + test: ["CMD", "./messenger", "healthcheck"] interval: 5s timeout: 3s retries: 20 diff --git a/go.mod b/go.mod index 99bf242..ff02335 100644 --- a/go.mod +++ b/go.mod @@ -3,15 +3,20 @@ module messenger go 1.22.2 require ( + github.com/golang-migrate/migrate/v4 v4.17.1 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.5.5 golang.org/x/crypto v0.22.0 ) require ( + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect - golang.org/x/sync v0.1.0 // indirect + go.uber.org/atomic v1.7.0 // indirect + golang.org/x/sync v0.5.0 // indirect golang.org/x/text v0.14.0 // indirect ) diff --git a/go.sum b/go.sum index 99d44c2..6a4ec1a 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,33 @@ +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dhui/dktest v0.4.1 h1:/w+IWuDXVymg3IrRJCHHOkMK10m9aNVMOyD0X12YVTg= +github.com/dhui/dktest v0.4.1/go.mod h1:DdOqcUpL7vgyP4GlF3X3w7HbSlz8cEQzwewPveYEQbA= +github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= +github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v24.0.9+incompatible h1:HPGzNmwfLZWdxHqK9/II92pyi1EpYKsAqcl4G0Of9v0= +github.com/docker/docker v24.0.9+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-migrate/migrate/v4 v4.17.1 h1:4zQ6iqL6t6AiItphxJctQb3cFqWiSpMnX7wLTPnnYO4= +github.com/golang-migrate/migrate/v4 v4.17.1/go.mod h1:m8hinFyWBn0SA4QKHuKh175Pm9wjmxj3S2Mia7dbXzM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw= +github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= @@ -11,19 +36,41 @@ github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= +github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= +github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= +golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.10.0 h1:tvDr/iQoUqNdohiYm0LmmKcBk+q86lb9EprIUFhHHGg= +golang.org/x/tools v0.10.0/go.mod h1:UJwyiVBsOA2uwvK/e5OY3GTpDUJriEd+/YlqAwLPmyM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/src/database.go b/src/database.go index cd28812..42ce63e 100644 --- a/src/database.go +++ b/src/database.go @@ -2,16 +2,19 @@ package main import ( "context" + "database/sql" "embed" "errors" - "fmt" "os" - "sort" "strings" "time" + "github.com/golang-migrate/migrate/v4" + pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5" + "github.com/golang-migrate/migrate/v4/source/iofs" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" + _ "github.com/jackc/pgx/v5/stdlib" ) //go:embed migrations/*.sql @@ -50,50 +53,44 @@ func openDatabase(ctx context.Context) (*pgxpool.Pool, error) { db.Close() return nil, err } - if err = applyMigrations(ctx, db); err != nil { + if err = runMigrations(url, "up"); err != nil { db.Close() return nil, err } return db, nil } -func applyMigrations(ctx context.Context, db *pgxpool.Pool) error { - files, err := migrationFiles.ReadDir("migrations") +// runMigrations uses versioned up/down SQL embedded in the API binary. +// "down" rolls back exactly one version and is an explicit operator command. +func runMigrations(url, direction string) error { + source, err := iofs.New(migrationFiles, "migrations") if err != nil { return err } - sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() }) - tx, err := db.Begin(ctx) + sqlDB, err := sql.Open("pgx", url) if err != nil { return err } - defer tx.Rollback(ctx) - if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(20426002)"); err != nil { + driver, err := pgxmigrate.WithInstance(sqlDB, &pgxmigrate.Config{}) + if err != nil { + sqlDB.Close() return err } - if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)"); err != nil { + m, err := migrate.NewWithInstance("iofs", source, "pgx5", driver) + if err != nil { + sqlDB.Close() return err } - for _, file := range files { - var exists bool - if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)", file.Name()).Scan(&exists); err != nil { - return err - } - if exists { - continue - } - sql, readErr := migrationFiles.ReadFile("migrations/" + file.Name()) - if readErr != nil { - return readErr - } - if _, err = tx.Exec(ctx, string(sql)); err != nil { - return fmt.Errorf("migration %s: %w", file.Name(), err) - } - if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", file.Name()); err != nil { - return err - } + defer m.Close() + if direction == "down" { + err = m.Steps(-1) + } else { + err = m.Up() } - return tx.Commit(ctx) + if errors.Is(err, migrate.ErrNoChange) { + return nil + } + return err } func uniqueViolation(err error) bool { diff --git a/src/main.go b/src/main.go index e0d512c..df92709 100644 --- a/src/main.go +++ b/src/main.go @@ -110,6 +110,32 @@ func serverAddress() string { } func main() { + if len(os.Args) > 1 { + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + client := http.Client{Timeout: 2 * time.Second} + response, err := client.Get("http://127.0.0.1:8080/health/ready") + if err != nil { + os.Exit(1) + } + response.Body.Close() + if response.StatusCode != http.StatusOK { + os.Exit(1) + } + return + } + if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") { + log.Fatal("usage: messenger migrate up|down") + } + url, err := databaseURL() + if err != nil { + log.Fatal(err) + } + if err = runMigrations(url, os.Args[2]); err != nil { + log.Fatal(err) + } + log.Printf("migration %s complete", os.Args[2]) + return + } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) db, err := openDatabase(ctx) cancel() diff --git a/src/migrations/000001_initial.down.sql b/src/migrations/000001_initial.down.sql new file mode 100644 index 0000000..a3ba4f2 --- /dev/null +++ b/src/migrations/000001_initial.down.sql @@ -0,0 +1,5 @@ +DROP TABLE IF EXISTS sessions; +DROP TABLE IF EXISTS messages; +DROP TABLE IF EXISTS chat_members; +DROP TABLE IF EXISTS chats; +DROP TABLE IF EXISTS users; diff --git a/src/migrations/001_initial.sql b/src/migrations/000001_initial.up.sql similarity index 66% rename from src/migrations/001_initial.sql rename to src/migrations/000001_initial.up.sql index 2962c55..b00ad15 100644 --- a/src/migrations/001_initial.sql +++ b/src/migrations/000001_initial.up.sql @@ -1,33 +1,32 @@ -CREATE TABLE users ( +CREATE TABLE IF NOT EXISTS users ( id uuid PRIMARY KEY, username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), password_hash bytea NOT NULL, - password_salt bytea NOT NULL, created_at timestamptz NOT NULL ); -CREATE TABLE chats ( +CREATE TABLE IF NOT EXISTS chats ( id uuid PRIMARY KEY, title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), created_at timestamptz NOT NULL ); -CREATE TABLE chat_members ( +CREATE TABLE IF NOT EXISTS chat_members ( chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES users(id), PRIMARY KEY (chat_id,user_id) ); -CREATE INDEX chat_members_user_idx ON chat_members(user_id,chat_id); -CREATE TABLE messages ( +CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members(user_id,chat_id); +CREATE TABLE IF NOT EXISTS messages ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id), sender_id uuid NOT NULL REFERENCES users(id), text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), created_at timestamptz NOT NULL ); -CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id); -CREATE TABLE sessions ( +CREATE INDEX IF NOT EXISTS messages_history_idx ON messages(chat_id,created_at,id); +CREATE TABLE IF NOT EXISTS sessions ( token_hash bytea PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id), expires_at timestamptz NOT NULL ); -CREATE INDEX sessions_expiry_idx ON sessions(expires_at); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expires_at); diff --git a/src/user.go b/src/user.go index 594f8e7..a535ce3 100644 --- a/src/user.go +++ b/src/user.go @@ -41,6 +41,7 @@ func (s *userStore) create(ctx context.Context, username, displayName, password if err != nil { return User{}, err } + packedHash := append(salt, hash...) user := User{ ID: uuid.New().String(), Username: username, @@ -48,7 +49,7 @@ func (s *userStore) create(ctx context.Context, username, displayName, password CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - _, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,password_salt,created_at) VALUES($1,$2,$3,$4,$5,$6)", user.ID, user.Username, user.DisplayName, hash, salt, user.CreatedAt) + _, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, packedHash, user.CreatedAt) return user, err } @@ -60,17 +61,20 @@ func (s *userStore) getByID(ctx context.Context, id string) (User, error) { func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) { var user User - var hash, salt []byte - err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash,password_salt FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash, &salt) + var packedHash []byte + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash) if errors.Is(err, pgx.ErrNoRows) { return User{}, false, nil } if err != nil { return User{}, false, err } - actual, err := derivePassword(password, salt) + if len(packedHash) != 64 { + return User{}, false, errors.New("invalid password hash format") + } + actual, err := derivePassword(password, packedHash[:32]) if err != nil { return User{}, false, err } - return user, subtle.ConstantTimeCompare(hash, actual) == 1, nil + return user, subtle.ConstantTimeCompare(packedHash[32:], actual) == 1, nil } diff --git a/tests/session_expiry.py b/tests/session_expiry.py deleted file mode 100644 index e155c83..0000000 --- a/tests/session_expiry.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python3 -"""Run against a test stack configured with SESSION_TTL_SECONDS=2.""" -import time -from client import Client, arguments, check, run - - -def main(): - args = arguments('Check that a short lived session expires') - client = Client(args.base_url, args.ca_file) - actor = client.user('expiry') - client.call('GET', '/api/v1/users/me', actor=actor, schema='User') - time.sleep(3) - client.call('GET', '/api/v1/users/me', 401, actor=actor) - print('PASS: expired Bearer token was rejected') - - -if __name__ == '__main__': - run(main)